1

我有一個密碼字段,在它旁邊有一個passwordStrengthMeter元素指令。我希望passwordStrengthMeter能夠觀察對密碼字段的更改並實時更新,而不僅僅是模糊或密碼字段的模型通過驗證。如何在有效之前觀看ngModel值?

我在密碼字段上使用Angular驗證,我發現我的指令無法觀察到密碼字段的更改,直到密碼字段有效。我想要密碼驗證保持不變,但我也想要實時強度指示。我該如何做這項工作?以下是我迄今爲止...

HTML:

<input class="control" type="password" name="password" placeholder="Password" ng-model="account.password" 
     ng-minlength="8" ng-maxlength="15" ng-pattern="VALIDATION_PATTERNS.passwordStrength" required ng-focused /> 
<password-strength-meter password-field="account.password"></password-strength-meter> 

而且指令:

angular.module('app.directives').directive('passwordStrengthMeter', function() { 
    'use strict'; 

    return { 
     restrict: 'E', 
     replace: true, 
     template: '<div class="password-strength-meter"></div>', 
     link: function(scope, element, attrs) { 
      // Map scores to CSS classes. 
      var scoreClasses = { 
       0: 'blank', 
       1: 'weak', 
       2: 'moderate', 
       3: 'strong', 
       4: 'very-strong' 
      }; 

      var scorer = function() { 
       // Get password value. 
       var password = scope.$eval(attrs.passwordField); 

       // Calculate a score. 
       // TODO Replace this with an actual calculation. 
       return password.length; 
      } 
      scope.$watch(scorer, function(score) { 
       // Remove any score classes for the element. 
       for (var i in scoreClasses) { 
        element.removeClass(scoreClasses[i]); 
       } 

       // Set class based on score. 
       element.addClass(scoreClasses[score]); 
      }); 
     } 
    }; 
}); 

回答

0

看來,在密碼輸入字段設置

ng-model-options="{allowInvalid: true}" 

解決這個問題。

如果任何人有一個替代或更好的解決方案,隨時張貼。

+1

[docs](https://docs.angularjs.org/api/ng/directive/ngModelOptions),供將來參考。 – Blazemonger 2014-11-20 20:17:26