2015-03-03 98 views
0

我想匹配兩個文本字段密碼whick看起來是這樣的:預期Angularjs:匹配密碼太快?

pwCheck.js

angular.module('installApp') 
.directive('pwCheck', function ($http) { 
    return { 
    require: 'ngModel', 
    link: function (scope, elem, attrs, ctrl) { 
     var firstPassword = '#' + attrs.pwCheck; 
     elem.add(firstPassword).on('keyup', function() { 
      scope.$apply(function() { 
       ctrl.$setValidity('pwmatch', elem.val() === $(firstPassword).val()); 
      }); 
     }); 
     } 
    } 
}); 

accounts.html

<label>{{label.password}}</label> 
    <input type="password" class="form-control" id="pw1" name="pw1" ng-model-options="{updateOn:'blur'}" ng-model="user.password" required ></input> 

<label>{{label.retypePassword}}</label> 
    <input type="password" class="form-control" id="pw2" name="pw2" ng-model-options="{updateOn:'blur'}" ng-model="pw2" ng-required="" pw-check="pw1"></input> 

<div class="msg-block" ng-show="signupform.$error"><img src = "./images/error-icon.png" width = "25" height = "25" ng-show="signupform.pw2.$error.pwmatch"></img><span class="msg-error" ng-show="signupform.pw2.$error.pwmatch">Passwords don't match.</span></div> 

上面的代碼工作正常,但給一個可怕的用戶體驗。發生這種情況是因爲當我輸入第一個文本字段時,即使用戶沒有完成輸入,「密碼不匹配」消息也會顯示。

問題是,在用戶輸入完成之前驗證發生得太快。

我試圖通過加入ng-model-options="{updateOn:'blur'}"來解決這個問題,但問題仍然存在。

幫助!在此先感謝

+2

爲什麼不把'keyup'改成'模糊' – 2015-03-03 04:09:35

+0

我試過了,謝謝它現在正在工作。 。 – 2015-03-03 04:13:32

+1

如果使用angular 1.3+,您還可以使用ng-model-options debounce選項進行研究。 – 2015-03-03 04:23:22

回答

1

使用模糊,而不是鍵。 嘗試以下操作:

angular.module('installApp') 
.directive('pwCheck', function ($http) { 
    return { 
    require: 'ngModel', 
    link: function (scope, elem, attrs, ctrl) { 
     var firstPassword = '#' + attrs.pwCheck; 
     elem.on('blur', function() { 
      scope.$apply(function() { 
       ctrl.$setValidity('pwmatch', elem.val() === $(firstPassword).val()); 
      }); 
     }); 
     } 
    } 
}); 

注意:上ELEM刪除add方法。會拋出錯誤,因爲在元素上沒有定義添加方法。