It turns out that there's a very elegant solution to this, but it's not well documented.
Formatting model values for display can be handled by the |
operator and an angular formatter
. It turns out that the ngModel that has not only a list of formatters but also a list of parsers.
ng-model
to create the two-way data binding<input type="text" ng-model="foo.bar"></input>
ngModel
controllermodule.directive('lowercase', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
...
}
};
});
link
method, add your custom converters to the ngModel
controllerfunction fromUser(text) {
return (text || '').toUpperCase();
}
function toUser(text) {
return (text || '').toLowerCase();
}
ngModel.$parsers.push(fromUser);
ngModel.$formatters.push(toUser);
ngModel
<input type="text" lowercase ng-model="foo.bar"></input>
Here's a working example that transforms text to lowercase in the input
and back to uppercase in the model
The API Documentation for the Model Controller also has a brief explanation and an overview of the other available methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With