我想基于自定义布尔值设置表单元素的有效性。请考虑以下密码字段:

<input type="password" name="password" ng-model="user.password" required>
<input type="password" name="passwordRepeat" ng-model="user.passwordRepeat" required>


如果重复的密码与原始密码匹配,我想将第二个输入字段标记为有效。就像是:

<input type="password" name="passwordRepeat" ng-model="user.passwordRepeat" my-validation-check="user.passwordRepeat === user.password" required>


为此,我找不到任何Angular指令。有任何想法吗?也许为此创建我自己的指令?不幸的是,我不是Angular专家...应该是这样的:

angular.module('app').directive('myValidationCheck', function() {
    return {
        scope: true,
        require: 'ngModel',
        link: function(scope, elm, attrs, ngModel) {
            // eval and watch attrs.myValidationCheck
            // and use ngModel.$setValidity accordingly
        }
    };
});


谢谢!

最佳答案

我已经花了很多时间根据下面的答案来找到最佳答案(非常感谢!)。对我来说,诀窍很简单:

angular.module('myApp').directive('myValidationCheck', function() {
    return {
        scope: {
            myValidationCheck: '='
        },
        require: 'ngModel',
        link: function(scope, elm, attrs, ngModel) {

            scope.$watch('myValidationCheck', function(value) {
                ngModel.$setValidity('checkTrue', value ? true : false);
            });

        }
    };
});


对于

<input type="password" name="passwordRepeat" my-validation-check="user.password === user.passwordRepeat" ng-model="user.passwordRepeat" required>


这确实很灵活。您可以在my-validation-check中使用所需的任何内容,例如确保选中一个复选框,或者更复杂的表达式为true。

希望这不仅对我自己有帮助.. :-)

10-04 21:28
查看更多