码迷,mamicode.com
首页 > Web开发 > 详细

angularJS中自定义验证指令中的$parsers and $formatters

时间:2015-11-09 15:43:00      阅读:849      评论:0      收藏:0      [点我收藏+]

标签:

本文翻译自:$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 这里.

  

 

angularJS中自定义验证指令中的$parsers and $formatters

标签:

原文地址:http://www.cnblogs.com/walle2/p/4949829.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!