AngularJS $setViewValue() Not Responding in $parsers.push()

风格不统一 提交于 2019-12-08 02:27:22

问题


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?

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.


回答1:


$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[] 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.

http://jsfiddle.net/GSTC5/4/

The ngModelController.$setViewValue() should only be called by the DOM change event.

This should've been a job for the ngModelController.$formatters[], but sadly the formatters aren't applied when the change is initiated by $setViewValue()



来源:https://stackoverflow.com/questions/20101054/angularjs-setviewvalue-not-responding-in-parsers-push

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!