javascript 什么 * 是 * ngModel.$validators 管道?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25769072/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What *is* the ngModel.$validators pipeline?
提问by Andrew Gray
While performing some basic research on custom client-side validation in Angular.js, I was reading the ngModel.NgModelControllerdocumentation, and found the following cryptic line:
在对 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.
$setValidity(validationErrorKey, isValid); 更改有效性状态,并通知表单。
这个方法可以在 $parsers/$formatters 中调用。但是,如果可能,请使用旨在自动调用此方法的 ngModel.$validators 管道。
A couple of hours and many Google (and StackOverflow!) searches later, I have found nothing about this ngModel.$validators
pipeline anywhere. All custom validation examples use the $parsers/$formatters
setup as below:
几个小时和许多谷歌(和 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);
});
},
Question:The Angular documentation states that the above code is notthe best practice, and that this mythical ngModel.$validators
pipline is the correct way to go. I have failed to find any information on this better practice. How does one use ngModel.$validators
to correctly implement this custom clientside validation?
问题:Angular 文档指出,上面的代码不是最佳实践,这个神话般的ngModel.$validators
管道是正确的方法。我没有找到有关这种更好做法的任何信息。如何使用ngModel.$validators
正确实现此自定义客户端验证?
采纳答案by rob
$validators
are new to Angular 1.3. This blog post gives a good explanation on how to use them: http://www.yearofmoo.com/2014/09/taming-forms-in-angularjs-1-3.html#the-validators-pipeline
$validators
是 Angular 1.3 的新手。这篇博文很好地解释了如何使用它们:http: //www.yearofmoo.com/2014/09/taming-forms-in-angularjs-1-3.html#the-validators-pipeline
The basic idea is that you add a function onto ngModel.$validators
that returns a boolean
specifying whether the model is valid.
基本思想是您添加一个函数ngModel.$validators
,该函数返回一个boolean
指定模型是否有效的函数。
Then you can refrence that validator in your HTML the same way you would reference any built in validators. e.g.
然后,您可以像引用任何内置验证器一样,在 HTML 中引用该验证器。例如
<div ng-if="myForm.myField.$error.myValidator">
some error message here
</div>