在以编程方式更改模型时,AngularJS自定义验证不会触发

Jim*_*per 15 angularjs

我创建了一个自定义验证器,要求过去的日期.手动输入日期时,验证似乎很有效.但是,如果我输入以编程方式更改日期(直接更改模型而不是在字段中键入),则验证不会触发.

我相信我正在按照文档中的指示进行自定义验证指令. 这是一个说明问题的jsFiddle.在小提琴中,如果单击"以编程方式更改日期"按钮,则可以看到未显示验证错误(但如果您手动更改它则会显示).这是指令代码(也在小提琴中):

myApp.directive('pastDate', function() {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function (scope, element, attrs, ctrl) {
            ctrl.$parsers.unshift(function (viewValue) {
                var today = new Date();
                today = new Date(today.getFullYear(), today.getMonth(), today.getDate());

                if (new Date(viewValue) < today) {
                    ctrl.$setValidity('pastDate', true);
                    return viewValue;
                }
                ctrl.$setValidity('pastDate', false);
                return undefined;
            });
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

yux*_*ang 18

模型绑定有两种方式,$parsers控制视图到模型方向$formatters的管道,并控制模型到视图方向的管道.在控制器中更新模型时,更改将通过$formatters管道.

我已将您的代码更新为:this,因此它处理两种方式.

myApp.directive('pastDate', function() {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function (scope, element, attrs, ctrl) {
            function validate (value) {
                var today = new Date();
                today = new Date(today.getFullYear(), today.getMonth(), today.getDate());

                if (new Date(value) < today) {
                    ctrl.$setValidity('pastDate', true);
                    return value;
                }
                ctrl.$setValidity('pastDate', false);
                return value;
            }
            ctrl.$parsers.unshift(validate);
            ctrl.$formatters.unshift(validate)
        }
    };
});
Run Code Online (Sandbox Code Playgroud)


M's*_*ph' 11

角度1.3以来的新答案提供了$validators属性.

从1.3开始,$parsers并且$formatters不应该再设置有效性,即使它仍然可能.

然后你的代码变得更简单:

myApp.directive('pastDate', function() {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function (scope, element, attrs, ctrl) {
            ctrl.$validators.pastDate = function(modelValue) { // 'pastDate' is the name of your custom validator ...
                var today = new Date();
                today = new Date(today.getFullYear(), today.getMonth(), today.getDate());
                return (new Date(modelValue) < today);
            }
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

更新了jsFiddle:http://jsfiddle.net/jD929/53/