Why does $setViewValue pass data through parsers?
I read in the AngularJS documentation:
$setViewValue(value)
It will update the $viewValue, then pass this value through each of the functions in $parsers, which includes any validators. The value that comes out of this $parsers pipeline, be applied to $modelValue and the expression specified in the ng-model attribute.
Can someone explain to me what it means where it says "pass this value through each of the functions in $parsers".
What parsers? Do these parsers have anything to do with HTML tags. The reason I ask is because my directive seems to be adding HTML tags somehow to the data.
No, $parsers don't have anything to do with the HTML tags.
$parsers
is a member of ngModelController. It's an array of functions. When viewValue
is changed (what you type into your form control element, eg <input>
), it will be parsed by each function in the $parsers
array, before settling on a final modelValue (the model in your controller).
Functions in the $parsers
array are commonly used to validate the input before setting the model. Usually, if user input is invalid, the change is rejected, and model is left at it's original state.
Take, for example, the required
directive, as defined natively by Angular, on form controls ( input
, select
, textarea
, etc.). This directive ensures that the model value is set to truthy value, and it will flag the model as invalid in case it doesn't pass the validation:
var validator = function(value) {
if (attr.required && ctrl.$isEmpty(value)) {
ctrl.$setValidity('required', false);
return;
} else {
ctrl.$setValidity('required', true);
return value;
}
};
ctrl.$parsers.unshift(validator);
In this example, the ctrl
is a reference to ngModelController.