以编程方式更改模型时不会触发AngularJS自定义验证 [英] AngularJS custom validation not firing when changing the model programmatically

查看:69
本文介绍了以编程方式更改模型时不会触发AngularJS自定义验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have created a custom validator for requiring a date to be in the past. The validation seems to work great when entering the date manually into the field. However, if I enter change the date programmatically (change the model directly as opposed to typing in the field), the validation does not fire.

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

I believe I am doing the custom validation directive as directed in the documentation. Here is a jsFiddle illustrating the problem. In the fiddle, if you click the "Change date programatically" button, you can see the validation error doesn't get displayed (but it does if you change it manually). Here is the directive code (also in the fiddle):

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;
            });
        }
    };
});

推荐答案

模型绑定有两种方法:$parsers控制视图到模型方向的管线,而$formatters控制模型的管线到视图的方向.当您在控制器中更新模型时,更改将通过$formatters管道进行.

There are two ways of the model binding, $parsers controls the pipeline of view-to-model direction, and $formatters controls the pipeline of the model-to-view direction. When you update the model in the controller, the change goes through the $formatters pipeline.

我已将您的代码更新为:,因此它可以双向处理.

I have updated your code to: this, so it handles both ways.

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)
        }
    };
});

这篇关于以编程方式更改模型时不会触发AngularJS自定义验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆