Set $modelValue without changing $viewValue

2019-09-01 06:36发布

问题:

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/