我正在写一个密码验证指令:
Directives.directive("passwordVerify",function(){ return { require:"ngModel", link: function(scope,element,attrs,ctrl){ ctrl.$parsers.unshift(function(viewValue){ var origin = scope.$eval(attrs["passwordVerify"]); if(origin!==viewValue){ ctrl.$setValidity("passwordVerify",false); return undefined; }else{ ctrl.$setValidity("passwordVerify",true); return viewValue; } }); } }; });
html:
<input data-ng-model='user.password' type="password" name='password' placeholder='password' required> <input data-ng-model='user.password_verify' type="password" name='confirm_password' placeholder='confirm password' required data-password-verify="user.password">
给定一个格式的2个密码字段,如果两个密码值相等,则该指令影响的字段有效。问题是它以一种方式起作用(即,当我在密码验证字段中键入密码时)。但是,当原始密码字段更新时,密码验证无效。
知道如何进行“双向绑定验证”吗?
这应该解决它:
视图:
<div ng-controller='Ctrl'> <form name='form'> <input data-ng-model='user.password' type="password" name='password' placeholder='password' required> <div ng-show="form.password.$error.required"> Field required</div> <input ng-model='user.password_verify' type="password" name='confirm_password' placeholder='confirm password' required data-password-verify="user.password"> <div ng-show="form.confirm_password.$error.required"> Field required!</div> <div ng-show="form.confirm_password.$error.passwordVerify"> Fields are not equal!</div> </form </div>
指示
var app = angular.module('myApp', []); app.directive("passwordVerify", function() { return { require: "ngModel", scope: { passwordVerify: '=' }, link: function(scope, element, attrs, ctrl) { scope.$watch(function() { var combined; if (scope.passwordVerify || ctrl.$viewValue) { combined = scope.passwordVerify + '_' + ctrl.$viewValue; } return combined; }, function(value) { if (value) { ctrl.$parsers.unshift(function(viewValue) { var origin = scope.passwordVerify; if (origin !== viewValue) { ctrl.$setValidity("passwordVerify", false); return undefined; } else { ctrl.$setValidity("passwordVerify", true); return viewValue; } }); } }); } }; });