javascript - Angularjs 确认密码指令 : why it does not see keyboard inputs?

标签 javascript angularjs angularjs-directive

我正在 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,您会看到两个值都已填充并且两个输入中的击键都被拾取。

来自Angular Forms guide :

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/

相关文章:

javascript - 防止 body 在移动 Safari/iPad/iOS 8 中滚动到顶部

javascript - 我的 if/else 条件没有正常显示

javascript - 更改 Controller 初始化中的范围不适用于指令

javascript - AngularJS 有没有办法在引导后动态注册指令

AngularJS : transcluding multiple sub elements in a single Angular directive

javascript - 带有三元运算符的附加赋值运算符

javascript - 如何处理正则表达式中的\(转义)字符?

javascript - AngularJS:如何在 View 中显示html数据?

angularjs - Protractor:在 Iframe 中测试 Angular 应用程序

javascript - 如何使用 ui-router 将对象从 1 $state 发送到另一个 $state