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

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

  

 

转载于:https://www.cnblogs.com/walle2/p/4949829.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值