angularJS中自定义验证指令中的$parsers and $formatters
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了angularJS中自定义验证指令中的$parsers and $formatters,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1459字,纯文字阅读大概需要3分钟。
内容图文
本文翻译自:$parsers and $formatters in Custom Validation Directives in Angular JS
在使用angularJS的应用中,有时候我们需要定义自己的表单验证。自定义验证在angularJS中是通过创建指令来实现的,该指令依赖于ng-model指令,主要是依赖于它的controller。
ng-model指令提供2个由函数组成的数组: $parsers 和 $formatters,这些函数用于实现自定义验证逻辑时调用。这两个数组的用途相似,但是使用场景不同。
$parsers
大部分情况下,使用$parsers来处理自定义都是不错的选择。当表单input的值被用户修改时,被添加到$parsers中的函数会被立即调用,举个栗子:
app.directive(‘evenNumber‘, function(){ return{ require:‘ngModel‘, link: function(scope, elem, attrs, ctrl){ ctrl.$parsers.unshift(checkForEven); function checkForEven(viewValue){ if (parseInt(viewValue)%2 === 0) { ctrl.$setValidity(‘evenNumber‘,true); } else{ ctrl.$setValidity(‘evenNumber‘, false); } return viewValue; } } }; });
这是一个简单的指令,检查textbox中输入的值是否为偶数,如果把这个验证指令用在textbox上,只要textbox的值发生改变,这个指令就会生效
$formatters
Formatters 仅在model被程序改变时被调用,当textbox中的值改变时是不会被调用的。翻不下去了,直接看英文吧 囧
Formatters are invoked when the model is modified in the code. They are not invoked if the value is modified in the textbox. $formatters are useful when there is a possibility of the value getting modified from the code. $formatters can be applied in the above directive using a simple statement:
ctrl.$formatters.unshift(checkForEven);
Now, the validation on the textbox containing the evenNumber is fired when the value is directly modified or even when the value is modified in the code.
A demo of the directive is available on 这里.
原文:http://www.cnblogs.com/walle2/p/4949829.html
内容总结
以上是互联网集市为您收集整理的angularJS中自定义验证指令中的$parsers and $formatters全部内容,希望文章能够帮你解决angularJS中自定义验证指令中的$parsers and $formatters所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。