Mohamed Ben HEnda
Mohamed Ben HEnda

Reputation: 2776

Difference between modelValue and viewValue

With a custom directive, a validation function is added to validate integer input

var INTEGER_REGEXP = /^\-?\d+$/;
app.directive('integer', function() {
  return {
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) {
      ctrl.$validators.integer = function(modelValue, viewValue) {
        if (ctrl.$isEmpty(modelValue)) {
          // consider empty models to be valid
          return true;
        }

        if (INTEGER_REGEXP.test(viewValue)) {
          // it is valid
          return true;
        }

        // it is invalid
        return false;
      };
    }
  };
});

Each function in the $validators object receives the modelValue and the viewValue.

What is the difference between modelValue and viewValue ?

Upvotes: 4

Views: 3441

Answers (1)

Jussi Kosunen
Jussi Kosunen

Reputation: 8307

It is possible to define $formatters and $parsers in your ngModelController. The viewValue is the value that the rendering directive uses to draw itself, the modelValue is what is stored in the scope once ngModel's $parser list hase been applied. If you change the value in the scope, ngModel will run that value through its $formatters which is then read by the rendering directive as a viewValue.

Often the viewValue is the string that is displayed in an input element whereas the modelValue is the value that has been parsed into the target format (a Date object in a datepicker directive, for example)

Upvotes: 4

Related Questions