我有指令验证用户输入的相同密码。但在内部指令中我想要setValidity = true
两个输入元素
.directive('equalsTo', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
scope.$watch(attrs.ngModel, function() {
console.log(ctrl.$viewValue);
debugger;
if ($('#' + attrs.id).val() === $(attrs.equalsTo).val()) {
ctrl.$setValidity('equalsTo', true);
//here I want to apply $(attrs.equalsTo).setValidity('equalsTo', true);
} else {
ctrl.$setValidity('equalsTo', false);
//here I want to apply $(attrs.equalsTo).setValidity('equalsTo', false);
}
});
}
};
});
我想在setValidity
$(attrs.equalsTo)
<input id="newPassword" name="newPassword" ng-model="newPassword" type="password"
class="form-control" placeholder="new password" ng-minlength="5" equals-to="#verifyNewPassword">
<input id="verifyNewPassword" name="verifyNewPassword" ng-model="verifyNewPassword" type="password"
class="form-control" placeholder="verify new password" equals-to="#newPassword">
答案 0 :(得分:1)
有一种更好的方法,传入依赖输入的ngModelController。所以html变成了
<input id="newPassword" name="newPassword" ng-model="newPassword" type="password"
class="form-control" placeholder="new password" ng-minlength="5" equals-to="form.verifyNewPassword">
<input id="verifyNewPassword" name="verifyNewPassword" ng-model="verifyNewPassword" type="password"
class="form-control" placeholder="verify new password" equals-to="form.newPassword">
这里我假设表格的名称为
<form name='form'>
将其替换为您的表单所具有的名称。
然后将指令定义更改为从其他ngModelController读取数据。
.directive('equalsTo', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
scope.$watch(attrs.ngModel, function() {
console.log(ctrl.$viewValue);
var otherController=scope.$eval(attrs.equalsTo);
if (ctrl.$viewValue===otherController.$viewValue) {
ctrl.$setValidity('equalsTo', true);
otherController.setValidity('equalsTo', true);
} else {
ctrl.$setValidity('equalsTo', false);
//here I want to apply
otherController.setValidity('equalsTo', false);
}
});
}
};
});