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 ?
It is possible to define $formatter
s and $parser
s 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)
链接地址: http://www.djcxy.com/p/77926.html