SuperUberDuper
SuperUberDuper

Reputation: 9633

Parsing the value of an input in angular breaks when using angular 1.3.x

Using angular 1.3.x, I have a parser in a directive assigned to an input.

When the user enters text into the directive the function that has been pushed to the $parses array is run. However when ngModel.$setViewValue(res); is called the same parse function is immediately called which didn't happen in angular 1.2.x

ngModel.$parsers.push(function (inputValue) {
    var originalVal = element.val();

    // do some logic to originalVal and set it as new ViewValue if changed

    if (originalVal != inputValue ) {
        ngModel.$setViewValue(res);
        ngModel.$render();
    }
});

Any ideas?

Upvotes: 0

Views: 856

Answers (1)

JoseM
JoseM

Reputation: 4302

The $parsers documentation states

Array of functions to execute, as a pipeline, whenever the control reads value from the DOM. Each function is called, in turn, passing the value through to the next. The last return value is used to populate the model. Used to sanitize / convert the value as well as validation. For validation, the parsers should update the validity state using $setValidity(), and return undefined for invalid values.

The emphasis is mine. So you need to return a value.

ngModel.$parsers.push(function (inputValue) {
    var originalVal = element.val();

    // do some logic to originalVal and set it as new ViewValue if changed

    if (originalVal != inputValue ) {
        ngModel.$setViewValue(res);
        ngModel.$render();
    }

    // make sure to return the updated view value
    return res;
});

I updated the sample fiddle to show that it works http://jsfiddle.net/dj6mX/1138/

Upvotes: 2

Related Questions