首页 > 解决方案 > AgnualrJs - $parsers.unshift 与 $parsers.push 的区别

问题描述

自定义指令之间ngModelCtrl.$parsers.unshift的确切区别是什么。ngModelCtrl.$parsers.push

model我想强制 Angular 在发生某些事情时验证表单,但不会对表单本身生效form。我试图设置Form.$setSubmitted,但我知道这不是应该做的方式。经过几次谷歌搜索后,我发现必须ngModelCtrl.$parsers.unshift在我的自定义验证指令中使用类似的东西。

我的指令有责任检查绑定到的数组的长度ng-model

return {
        restrict: 'A',
        require: 'ngModel',
        link: function ($scope, elem, attrs, ngModelCtrl) {

            ngModelCtrl.$parsers.push(function (viewValue) {
                // doesn't enter this function at all!
                console.log(viewValue);
            });

            ngModelCtrl.$validators.requiredCount = function (modelValue, viewValue) {
                // executed at the first time only at initialize
                return modelValue.length == attrs.requiredCount;
            };
        }
    };

以及我如何使用它:

<list orientation="vertical" type="PropertyValue" ng-model="Entity.PropertyValues" 
          dont-save 
          ng-required="PropertyTypeIdObject.Code === 'FixedValues'"
          required-count="1"></list>

本身是一个指令,list负责处理绑定到的数组ng-model

标签: javascriptangularjs

解决方案


解析器文档 parsersArray of functions

每当控件使用来自 DOM 的新 $viewValue 更新 ngModelController 时,作为管道执行的函数数组,通常通过用户输入。有关详细的生命周期说明,请参阅 $setViewValue()。请注意,当绑定的 ngModel 表达式以编程方式更改时,不会调用 $parsers。

这些函数按数组顺序调用,每个函数都将其返回值传递给下一个函数。最后一个返回值被转发到 $validators 集合。

所以,在你的代码中

 ngModelCtrl.$parsers.push(function (viewValue) {
      // doesn't enter this function at all!
      console.log(viewValue);
 });

您正在推送一个新function的数组parsers来验证ngModel controller

unshift现在,和之间的区别push

  1. Unshift并使shift整个数组移位sideways(通过从头开始添加和删除项目)
  2. Push并且pop不要使数组横向移动(因为它们在最后添加和删除项目)

所以,ngModelCtrl.$parsers.unshift insert你的功能first indexngModelCtrl.$parsers.pushinsert的功能last index


推荐阅读