我已经创建了一个验证指令,它确保在密码和验证密码字段中输入相同的数据,它工作正常如果我在其中输入内容,如果我输入密码然后删除它,它就不起作用。 在这里检查plunker http://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);
}
});
}
};
});
答案 0 :(得分:3)
删除密码后,将空字符串与未定义的值进行比较:
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);
}
答案 1 :(得分:0)
.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);
};
}
}
})
尝试此指令。