我已经创建了一个验证指令,它确保在密码和验证密码字段中输入相同的数据。如果我在其中键入一些内容,如果我键入密码然后删除它,它就不起作用。查看此处的plunkerhttp://plnkr.co/edit/tsNqEpMtLY1aEkxBjNcw?p=preview
Type something in password field -> Update btn will disabled
Clear the password field by pressing backspace -> Update btn still disabled
这是js代码
.directive('equalsTo', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
var sc = scope;
scope.$watch(attrs.ngModel, function() {
var eqCtrl = scope.$eval(attrs.equalsTo);
if (ctrl.$viewValue===eqCtrl.$viewValue) {
ctrl.$setValidity('equalsTo', true);
eqCtrl.$setValidity('equalsTo', true);
} else {
ctrl.$setValidity('equalsTo', false);
eqCtrl.$setValidity('equalsTo', false);
}
});
}
};
});
删除密码后,将空字符串与未定义的值进行比较:
ctrl.$viewValue===eqCtrl.$viewValue
您应该检查两个变量是否为空或未定义,然后表单有效:
if (ctrl.$viewValue===eqCtrl.$viewValue || (!!!ctrl.$viewValue && !!!eqCtrl.$viewValue)) {
ctrl.$setValidity('equalsTo', true);
eqCtrl.$setValidity('equalsTo', true);
} else {
ctrl.$setValidity('equalsTo', false);
eqCtrl.$setValidity('equalsTo', false);
}
http://plnkr.co/edit/QKOr2K7NXjOMGtnKdeWT?p=preview
.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
ngModel.$setValidity('equals', val1 === val2);
};
}
}
})
试试这个指令。