如何在ngModel值有效之前观看它?

时间:2014-11-20 20:03:53

标签: javascript angularjs validation angular-ngmodel angular-directive

我有一个密码字段,旁边有一个passwordStrengthMeter元素指令。我希望passwordStrengthMeter能够观察密码字段的变化并实时更新 - 不仅仅是模糊或密码字段的模型通过验证。

我在密码字段上使用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]);
            });
        }
    };
});

1 个答案:

答案 0 :(得分:0)

似乎设置

ng-model-options="{allowInvalid: true}"
密码输入字段上的

解决了这个问题。

如果有人有替代或更好的解决方案,请随时发布。