【问题标题】:How can I watch an ngModel value before it's valid?如何在 ngModel 值有效之前查看它?
【发布时间】:2015-01-18 20:07:46
【问题描述】:

我有一个密码字段,旁边有一个 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]);
            });
        }
    };
});

【问题讨论】:

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


    【解决方案1】:

    好像设置

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

    密码输入字段可以解决这个问题。

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

    【讨论】:

    • docs,供以后参考。
    猜你喜欢
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多