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.

Leave a Comment