原文: https://stackoverflow.com/questions/11616636/how-to-do-two-way-filtering-in-angularjs
------------------------------------------------------------------------------------------------------------
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
<input type="text" ng-model="foo.bar"></input>
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
<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.
ngModelCtrl
.) – Mark Rajcok Dec 19 ‘12 at 22:40$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. – Mark Rajcok Apr 12 ‘13 at 21:06