我做了一个简单的测试输入字段,但是我尝试转换模糊验证,但是我不知道要实现这一点,因为我对angularjs不太熟悉。
在这个例子中,任何人都可以帮助我验证一次模糊。
myJs:
angular.module('myApp', [])
.controller('FormController', function($scope) {
$scope.fields = [
{placeholder: 'Username', isRequired: true},
{placeholder: 'Password', isRequired: true},
{placeholder: 'Email (optional)', isRequired: false}
];
$scope.submitForm = function() {
alert("it works!");
};
});
的HTML:
<div ng-app="myApp">
<form name="signup_form" ng-controller="FormController" ng-submit="submitForm()" novalidate>
<div ng-repeat="field in fields" ng-form="signup_form_input">
<input type="text"
name="dynamic_input"
ng-required="field.isRequired"
ng-model="field.name"
placeholder="{{field.placeholder}}" />
<div ng-show="signup_form_input.dynamic_input.$dirty && signup_form_input.dynamic_input.$invalid">
<span class="error" ng-show="signup_form_input.dynamic_input.$error.required">The field is required.</span>
</div>
</div>
<button type="submit" ng-disabled="signup_form.$invalid">Submit All</button>
</form>
</div>
您可以简单地创建与相同名称的指令ngModel
。blur
在元素上添加一个事件,该事件会将的$dirty
状态更改ngModel
为true。通过在数组内添加回调,确保在对元素进行更改时将ngModel
的$dirty
状态更改为false ngModel.$viewChangeListeners
。
该指令如下所示:
.directive('ngModel', function() {
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel) {
elem.on('blur', function() {
ngModel.$dirty = true;
scope.$apply();
});
ngModel.$viewChangeListeners.push(function() {
ngModel.$dirty = false;
});
scope.$on('$destroy', function() {
elem.off('blur');
});
}
}
});
注意:不用担心自定义指令名称ngModel
是否与Angular的默认名称相同ngModel
,它将仅运行它们两者(不会覆盖它)。的scope.$on('$destroy')
监听器,消除了blur
当的范围被破坏的事件处理程序,例如,当路由变化,并且控制器被破坏,或当一个场被移除,其触发再次重建重复DOM元素(破坏由创建的子范围ng-repeat
)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句