问题描述
我有一个指令.它需要 ngModel
,并且在链接中,我应该能够使用 modelCtrl
参数来使用 $setViewValue();
和 $render();
结合返回更改我输入字段中的值并更新存储在 ngModel
中的值.不幸的是,当我将 modelCtrl
传递给我的逻辑函数时,我不能使用 $setViewValue();
和 $render();
,即使我将 modelCtrl
传递给函数.(见小提琴:http://jsfiddle.net/GSTC5/1/)
I have a directive. It requires ngModel
, and in the link, I should be able to use modelCtrl
parameter to use $setViewValue();
and $render();
in conjunction to return to change the value in my input field and update the value stored in ngModel
. Unfortunately, when I pass modelCtrl
into my logic function, I cannot use $setViewValue();
and $render();
, even though I pass modelCtrl
to the function. (See fiddle: http://jsfiddle.net/GSTC5/1/)
myApp.directive('demo', function() {
return {
require: 'ngModel',
restrict: 'EACM',
link: function(scope, element, attrs, modelCtrl) {
setAndRender(modelCtrl, "12345");
modelCtrl.$parsers.push(function(inputValue) {
return logic(inputValue, modelCtrl);
});
}
};
});
我在我写的另一个指令中有一些非常相似的工作,为什么它在这里失败?
I have something very similar working in another directive I wrote, why is it failing here?
更新
我相信错误在于 $setViewValue()
.我知道它会在从链接函数调用时做出响应,但是 $setViewValue
在从逻辑函数调用时会停止运行代码.
UPDATE
I believe that the fault lies with $setViewValue()
. I know it responds when it is called from the link function, but $setViewValue
stops the code from running when it is called from the logic function.
推荐答案
$setViewValue 从逻辑方法中调用,这会触发另一个 $parsers 循环,创建无限递归,导致 RangeError: Maximum call stack size exceeded代码>
$setViewValue is called from the logic method, which triggers another $parsers cycle, creating infinite recursion causing the RangeError: Maximum call stack size exceeded
ngModelController.$parsers[] 影响生成的 ngModelController.$modelValue,如果您还想影响 ngModelController.$viewValue,您可以直接设置 $viewValue 并调用 ngModelController.$render() 以允许组件更新 DOM.
ngModelController.$parsers[] affect the resulting ngModelController.$modelValue, if you also want to affect the ngModelController.$viewValue, you can set the $viewValue directly and call ngModelController.$render() to allow the component to update the DOM.
ngModelController.$setViewValue() 应仅由 DOM 更改事件调用.
The ngModelController.$setViewValue() should only be called by the DOM change event.
这应该是 ngModelController.$formatters[] 的工作,但遗憾的是,当 $setViewValue() 启动更改时,格式器并未应用
This should've been a job for the ngModelController.$formatters[], but sadly the formatters aren't applied when the change is initiated by $setViewValue()
这篇关于AngularJS $setViewValue() 在 $parsers.push() 中没有响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!