gpt4 book ai didi

javascript - AgnualrJs - $parsers.unshift 与 $parsers.push 的区别

转载 作者:行者123 更新时间:2023-11-30 14:35:07 27 4
gpt4 key购买 nike

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

当发生对模型生效但对表单本身无效的事情时,我想强制 Angular 验证表单。我尝试设置 Form.$setSubscribed 但我知道这不是应该做的方式。经过几次谷歌搜索后,我发现必须在我的自定义验证指令中使用类似 ngModelCtrl.$parsers.unshift 的内容。

我的指令有责任检查绑定(bind)到 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 本身是一个指令,负责处理绑定(bind)到 ng-model 的数组。

最佳答案

来自Parsers documentation 解析器是一个函数数组

Array of functions to execute, as a pipeline, whenever the control updates the ngModelController with a new $viewValue from the DOM, usually via user input. See $setViewValue() for a detailed lifecycle explanation. Note that the $parsers are not called when the bound ngModel expression changes programmatically.

The functions are called in array order, each passing its return value through to the next. The last return value is forwarded to the $validators collection.

所以,在你的代码中

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

您正在将新的函数推送到解析器数组以验证ngModel Controller

现在,unshiftpush 之间的区别:

  1. Unshift and shift make the whole array shift sideways (by adding and removing items from the beginning)
  2. Push and pop do NOT make the array shift sideways (because they add and remove items at the end)

因此,ngModelCtrl.$parsers.unshift 插入您的函数到第一个索引ngModelCtrl.$parsers.push code> 会将您的函数插入最后一个索引

关于javascript - AgnualrJs - $parsers.unshift 与 $parsers.push 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50539949/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com