我正在使用 Angular JS 制作注册表单,其中一个函数 ,regisChange()
通过ng-change
.
我有另一个名为的自定义指令equals
,用于$watch
检查密码字段并用于ngModel.$setValidity('equals', password1==password2)
设置表单的有效性。
理想情况下,每当用户更改他的密码字段时,我都希望该equals
指令在ng-change
. 这样可以在引用它equals
之前设置表单的有效性。ng-change
问题是如何$watch
在函数 in 之前对输入的更改执行 a ng-change
?
HTML
<div class="form-group">
<label for="register-password1">Password</label>
<input name="password1" type="password" class="form-control" ng-model="user.password1" required ng-minlength="6" ng-maxlength="20" equals="{{user.password2}}" ng-blur="fieldValidate('password1')" ng-change="regisChange('password1')">
<div class="error">{{error.password1}}</div>
</div>
<div class="form-group">
<label for="register-password2">Confirm Password</label>
<input name="password2" type="password" class="form-control" ng-model="user.password2" required equals="{{user.password1}}" ng-blur="fieldValidate('password2')" ng-change="regisChange('password2')">
<div class="error">{{error.password2}}</div>
</div>
等于指令
welcome.directive('equals', [function(){
return {
restrict: 'A', // only activate on element attribute
require: 'ngModel', // get a hold of NgModelController
link: function(scope, elem, attrs, ngModel) {
if(!ngModel) return; // do nothing if no ng-model
// watch own value and re-validate on change
scope.$watch(attrs.ngModel, function() {
validate();
});
// observe the other value and re-validate on change
attrs.$observe('equals', function (val) {
validate();
});
var validate = function() {
// values
var val1 = ngModel.$viewValue;
var val2 = attrs.equals;
// set validity
console.log('val1: '+val1)
console.log('val2: '+val2)
ngModel.$setValidity('equals', val1 === val2);
};
}
}
}]);
控制器中的 regisChange()
$scope.regisChange = function(fieldName){
console.log($scope.regisForm["password2"].$valid);
if($scope.regisForm[fieldName].$valid){
$scope.error[fieldName] = "";
}
};