gpt4 book ai didi

javascript - 什么是 ngModel.$validators 管道?

转载 作者:行者123 更新时间:2023-12-02 23:13:18 25 4
gpt4 key购买 nike

在 Angular.js 中对自定义客户端验证进行一些基础研究时,我正在阅读 ngModel.NgModelController文档,并发现以下神秘行:

$setValidity(validationErrorKey, isValid);Change the validity state, and notifies the form.

This method can be called within $parsers/$formatters. However, if possible, please use the ngModel.$validators pipeline which is designed to call this method automatically.

几个小时后,经过多次 Google(和 StackOverflow!)搜索,我在任何地方都没有找到任何有关此 ngModel.$validators 管道的信息。所有自定义验证示例都使用 $parsers/$formatters 设置,如下所示:

link: function (scope, elem, attr, ctrl) {
// Other necessary logic...

ctrl.$parsers.push(function () {
// Validation logic
ctrl.$setValidity('validation-type', true);
});

ctrl.$formatters.push(function () {
// Validation logic
ctrl.$setValidity('validation-type', true);
});
},

问题:Angular 文档指出上述代码不是最佳实践,并且这个神秘的 ngModel.$validators pipline 是正确的方法。我未能找到有关此更好实践的任何信息。如何使用 ngModel.$validators 来正确实现此自定义客户端验证?

最佳答案

$validators 是 Angular 1.3 中的新增内容。这篇博文很好地解释了如何使用它们:http://www.yearofmoo.com/2014/09/taming-forms-in-angularjs-1-3.html#the-validators-pipeline

基本思想是在 ngModel.$validators 上添加一个函数,该函数返回一个 boolean 指定模型是否有效。

然后您可以在 HTML 中引用该验证器,就像引用任何内置验证器一样。例如

<div ng-if="myForm.myField.$error.myValidator">
some error message here
</div>

关于javascript - 什么是 ngModel.$validators 管道?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25769072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com