How to create Custom Filters in AngularJS

Dhananjay Kumar / Tuesday, November 24, 2015

 

Have you ever used filters with the ng-repeat directive as shown in the listing below?
<div ng-controller="ProductController">
             <table class="table">              
                 <tr ng-repeat="a in products|filter:searchTerm">
                     <td>{{a.name}}</td>
                     <td>{{a.price}}</td>
                 </tr>
             </table>
        </div>
 
If so, then you’ve used a filter in an AngularJS application. AngularJS provides us many in-built directives like search. If required, AngularJS also allows us to create custom filters, which we’ll explore in this post.
AngularJS gives us a simple API to create a custom filter. You’ll remember that we use app.controller() to create controllers and app.module() to create modules. In exactly the same way, AngularJS has given us the angular.filter API to create a custom filter in AngularJS.  
A custom filter can be created using the following syntax:
 
 
To create a custom filter, you need to do the following steps:

·         Create a filter using the app.filter by passing a custom filter name and a function as input parameters to the app.filter()

·         App.filter() will return a function

·         The returned function can take various optional input parameters

·         The returned function will have custom filter code and it will return the output.

 
Let us start with creating a very simple custom filter. We can apply this custom filter on a string and it will return the string with each character in a capital case.
MyApp.filter('toUpperCase', function () {
 
    return function (input)
    {
        var output = "";       
        output = input.toUpperCase();
        return output;
    }
})
 
We can use the toUpperCase custom filter in the view as shown the listing below:
  <div ng-controller="ProductController">
             <table class="table">              
                 <tr ng-repeat="a in products|filter:searchTerm">
                     <td>{{a.name|toUpperCase}}</td>
                     <td>{{a.price}}</td>
                 </tr>
             </table>
        </div>
 
We need to keep in mind that the name of the custom filter is case sensitive. The above-created view is reading data from the controller as shown the listing below:
MyApp.controller("ProductController", function ($scope) {
 
    $scope.products = [

        { 'name': 'pen', 'price': '200' },

         { 'name': 'pencil', 'price': '400' },

          { 'name': 'book', 'price': '2400' },

           { 'name': 'ball', 'price': '400' },

            { 'name': 'eraser', 'price': '1200' },

    ];

 
})
 
Now we’ll get the product name rendered in a capital case on the view as shown in the image below:
The filter we created above does not take any input parameter, but let us say we want one there. This can be done very easily.  In the above filter, we are returning each character of the string in upper case. In the next filter, we will pass the position and only the character at that position will be converted to capital. So the filter which takes input parameter can be created as shown in the listing below:
MyApp.filter('toPositionUpperCase', function () {
 
    return function (input,position)
    {
        var output = [];       
        var capLetter = input.charAt(position).toUpperCase();
        for (var i = 0; i < input.length; i++) {
 
            if (i == position) {
                output.push(capLetter);
            } else {
                output.push(input[i]);
            }
 
        }
        output = output.join('');
        return output;
    }
})
 
We can use toPositionUpperCase custom filter in the view as shown the listing below. As you will notice that we are passing the input parameter to the custom filter using the colon.
<div ng-controller="ProductController">
             <table class="table">              
                 <tr ng-repeat="a in products|filter:searchTerm">
                     <td>{{a.name|toPositionUpperCase:1}}</td>
                     <td>{{a.price}}</td>
                 </tr>
             </table>
        </div>
We will get the second letter of product name rendered in the capital case on the view as shown in the image below:
 
Before we conclude this article, let us create a custom filter which will be applied on the collection of items. Let us say from the list of products, we want to filter all the products greater than a given price. We can write this custom filter as shown in the listing below:
MyApp.filter('priceGreaterThan', function () {
 
    return function (input, price) {
        var output = [];
        if (isNaN(price)) {
 
            output = input;
        }
        else {
            angular.forEach(input, function (item) {
 
                if (item.price > price) {
                    output.push(item)
                }
            });
        }
        return output;
    }
})
 
We can use the custom filter on the view as shown in the listing below. We are passing the price parameter from the input type text box.
<h1>With Custom Filter</h1>
       
    <div ng-controller="ProductController">
<input type="number" class="form-control" placeholder="Search here" ng-model="priceterm" />
            <br/>
            <table class="table">
                <tr ng-repeat="b in products|priceGreaterThan:priceterm">
                    <td>{{b.name}}</td>
                    <td>{{b.price}}</td>
                </tr>
            </table>
</div>
 
 With this we will get a filtered array on the view as shown in the image below:
So there you have it – that’s how to create a custom filter! It’s easy – they’re nothing but functions that take one input and optional parameters to return a function. I hope you enjoyed reading!
 
Deliver modern, responsive web applications with no limits on browsers, devices, and platforms with Infragistics jQuery& HTML5 controls. Download Free Trial now and see their power in action!