原文:
------------------------------------------------------------------------------------------------------------
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.
1. Use ng-model
to create the two-way data binding
2. Create a directive in your angular module that will be applied to the same element and that depends on the ngModel
controller
module.directive('lowercase', function() { return { restrict: 'A', require: 'ngModel', link: function(scope, element, attr, ngModel) { ... } }; });
3. Within the link
method, add your custom converters to the ngModel
controller
function fromUser(text) { return (text || '').toUpperCase(); } function toUser(text) { return (text || '').toLowerCase(); } ngModel.$parsers.push(fromUser); ngModel.$formatters.push(toUser);
4. Add your new directive to the same element that already has the ngModel
Here's a that transforms text to lowercase in the input
and back to uppercase in the model
The also has a brief explanation and an overview of the other available methods.
ngModelCtrl
.) –$scope
directly, that's what the model will be set to... until the user interacts with the textbox. At that point, any parsers can then affect the model value. In addition to a parser, you could add a $watch to your controller to transform the model value. –