app.directive("pwCheck", function () {
alert('hey');
return {
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
var firstPassword = '#' + attrs.pwCheck;
elem.add(firstPassword).on('keyup', function () {
scope.$apply(function () {
// console.info(elem.val() === $(firstPassword).val());
ctrl.$setValidity('pwmatch', elem.val() === $(firstPassword).val());
});
});
}
}
});
我有一个注册表单,用户必须输入密码和确认密码,我的问题是我的指令不能验证确认密码中的密码,检查密码是否相同,是否有另一种实现方式像ng-pattern这样的验证来检查输入是否相同?提前感谢。
答案 0 :(得分:2)
更好的方法是$validators
管道。但是,这也是以指令的形式实现的。 Angular 1.3中引入了此功能。旧的时尚方式是使用$parsers
和/或$formatters
。验证器管道的巨大优势在于您可以同时访问viewValue和modelValue。只需将密码传递给指令并添加新的验证器。
var app = angular.module('myApp', []);
app.controller('TestCtrl', TestController);
function TestController() {
var vm = this;
vm.password = '';
vm.confirmPassword = '';
}
app.directive('confirmPassword', ConfirmPassword);
function ConfirmPassword() {
var linkFn = function(scope, element, attributes, ngModel) {
ngModel.$validators.confirmPassword = function(modelValue) {
return modelValue == scope.password;
};
scope.$watch("password", function() {
ngModel.$validate();
});
};
return {
require: "ngModel",
scope: {
password: "=confirmPassword"
},
link: linkFn
};
};

input {
display: block;
margin-top: 5px;
margin-bottom: 10px;
}
.error {
color: red;
font-weight: bold;
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<div ng-app="myApp" ng-controller="TestCtrl as testCtrl">
<form name="myForm">
<label for="password">Password</label>
<input id="password" name="password" ng-model="testCtrl.password" type="password" />
<label for="confirmPassword">Confirm Password</label>
<input id="confirmPassword" name="confirmPassword" ng-model="testCtrl.confirmPassword" data-confirm-password="testCtrl.password" type="password" />
<span class="error" ng-show="myForm.confirmPassword.$invalid && !myForm.confirmPassword.$pristine">Passwords do not match!</span>
</form>
</div>
&#13;
这将检查两个密码是否匹配。如果密码不匹配,则有效性将为false。在这种情况下,我显示错误消息。