我正在 Angular.js 中构建自己的“确认密码”指令。我从这个 pen 得到灵感.
我的指令:
directives.directive('pwCheck', function(){
return {
require: 'ngModel',
link: function(scope, elem, attrs, ctrl){
var pw1 = attrs.pwCheck;
var pw2 = attrs.ngModel;
scope.$watchGroup([pw1,pw2],function(value){
console.log(value);
ctrl.$setValidity('pwmatch', value[0] === value[1]);
});
}
}
});
我的表格:
<input type="password" class="form-control" name="newpassword" placeholder="Type your new password" ng-model="newpassword"
ng-pattern="/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])/"
ng-minlength="8" ng-maxlength="20" ng-required="" />
和:
<input type="password" class="form-control" name="renewpassword" id="renwewpassword" placeholder="Type your new password again"
ng-model="renewpassword" ng-required="" pw-check="newpassword" />
但是,watchGroup
似乎没有捕捉到“newpassword”中的变化(击键)。
指令中的 console.log()
将为 value[0]
打印 undefined
,同时为 value 打印正确的输入[1]
.
我不知道问题出在哪里。有什么线索吗?
最佳答案
我设置了一个 fiddle使用您的代码,它似乎工作正常。但请记住,除非满足所有验证,否则不会填充第一个输入的 ng-model
:
ng-pattern="/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])/" ng-minlength="8" ng-maxlength="20"
如果您使用有效密码进行测试,例如ABCDabcd1234
,您会看到两个值都已填充并且两个输入中的击键都被拾取。
The value of ngModel won't be set unless it passes validation for the input field. For example: inputs of type email must have a value in the form of user@domain.
关于javascript - Angularjs 确认密码指令 : why it does not see keyboard inputs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32933714/