Angular.js: creating filters

Playing with Angular.js here. The learning curve is pretty steep in the beginning, but the result is worth it, imo.

Filters allow to apply various data transformations on the view, making it easy to either actually filter the data, or turn it into something else.

To create a filter, you need to add a .filter method to a module. 

Module in angular is something like a utility class, containing one or more of the following: services, directives, filters, or other modules.

 So, to start, create a new js file, name it filters.js (just for this example), with this code:

 

angular.module('filters', [])
    .filter('minLen', function () {
        return function (input, minLen, message) {
            minLen = minLen || 0;
            message = message || 'Too short';

            if (typeof (input) === 'undefined' || input.length < minLen)
                return message;
            return input;
        }
    });

    

This creates a new module, named ‘filters’ (this is what angular uses to find and inject it later on), and adds a filter ‘minLen’ to the module.

Filter should return a function, doing some input processing. This filter will also take min length and error message parameters, which are optional.

Then add this html inside a <body> tag:

<input type="input" ng-model="filteredInput">
<span>{{filteredInput | minLen:3:'make it longer'}}</span>

<script src="Scripts/angular.min.js" type="text/javascript"></script>
<script src="Scripts/Modules/filters.js" type="text/javascript"></script>

<script type="text/javascript">
    angular.element(document).ready(function () {
        angular.bootstrap(document, ['filters']);
    });
</script>

 

 This creates an input field, and binds it to the ‘filteredInput’ field inside a $scope (angular variable, which contains the data to be consumed by views).

Span field will be bound to the same field, and we’ll apply the filter to the output.

The code in the end calls a boot strap, initialization code that tells angular to run, treating ‘document’ as a boundary, and load the ‘filters’ module.

See the working version here: http://jsfiddle.net/etcoding/wURVY/5/

Leave a Reply

Your email address will not be published. Required fields are marked *