Set $modelValue without changing $viewValue

◇◆丶佛笑我妖孽 提交于 2019-12-13 04:45:05

问题


In angular 1.2 I need to be able to update the $modelValue without affecting the $viewValue. I want the internal value to be one value, while what the user sees to be another. The problem I am having is setting the $modelValue ends up setting the $viewValue on the next digest. My current work-around is using $timeout to set the $viewValue in the next digest.

//...

link: function(scope, elem, attrs, ctrl) {

    //...

    var setter = $parse(attrs.ngModel).assign;

    scope.$watch(attrs.otherValue, function(){
        var viewValue = ctrl.$viewValue;
        setter(scope, validate()); // validate returns undefined or value if valid
        $timeout(function(){
            if(ctrl.$viewValue !== viewValue){
                ctrl.$viewValue = viewValue;
                ctrl.$render();
            }
        });
    });

    //...

}

//...

Basically, I want to set the internal value of one with when another field changes in Angular 1.2

Fiddle (with ugly $timeout workaround): http://jsfiddle.net/TheSharpieOne/q1s7Lf7z/1/

TL;DR
Setting $modelValue outside of $parser/$formatter pipelines changes $viewValue, where I am wanted it to only change $modelValue (the internal value).


回答1:


When anything triggers the model to change, something like setter(scope, validate()); in the example above, it will trigger the $formatters to run. The $formatters are passed the $modelValue and can return a value that will be used for the $viewValue. Knowing this, you can use a simple function that just returns the $viewValue in the formatter. With this, updating the model programmatically will not affect the $viewValue, and thus not change the value that appears in <inputs>

ctrl.$formatters.push(formatter)

function formatter(modelValue){
    return ctrl.$viewValue;
}

For the example in the question, you would want to return the $viewValue only when the $modelValue is undefined. For that you can use this:

ctrl.$formatters.push(formatter)

function formatter(modelValue){
    return modelValue === undefined? ctrl.$isEmpty(ctrl.$viewValue)? undefined : ctrl.$viewValue : modelValue;
}

Working example: http://jsfiddle.net/TheSharpieOne/q1s7Lf7z/17/



来源:https://stackoverflow.com/questions/27491300/set-modelvalue-without-changing-viewvalue

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