Creating Custom Filters In AngularJS

Introduction

AngularJS filters cover many common uses such as formatting dates and currencies, limiting the number of items to be displayed, etc. The filters are helpful to how we may improve the workflow while building Angular apps.

In my previous article, we saw built-in AngularJS filters. We can also write our own custom filter. To create custom filter, we need to just register the filter in factory function in our module. This uses the "filterProvider" internally. By default new filter function takes the input value as the first argument and factory function will return the new filter. We can also pass additional arguments to the filter function.

The filter function should be stateless i.e. it should be pure function. AngularJS execute the filter function based on filter input.

The following are some rules to set the filter name:

  • Name with special character (like hyphens and dots) is not allowed.
  • If we want to add namespace to filter, we can use capitalization or underscores.
  • Filter Name must not be the same as standard AngularJS filters.

AngularJS has built-in method called "filter", which can help us to create custom filter.

Syntax:

    app.filter('name of filter', function () {
       return function () {
          return;
       };
    });

The returned functions in filter are getting invoked every time when AngularJS call the filter. It means that their is a two-way binding for our filter. When user makes any changes in expression, the filter runs again and updates the data.

Let us take a simple example of creating custom filter that converts our string to upper case. However this filter is already contained by the AngularJS library.

Custom filter

  1. app.filter('toUppercase', function () {  
  2.    returnfunction (item) {  
  3.       returnitem.toUpperCase();  
  4.    };  
  5. });  
Controller
  1. app.controller("demoController", ['$scope', function ($scope) {  
  2.    $scope.myName = "Jignesh Trivedi"  
  3. }]);  
HTML
  1. <div ng-controller="demoController"style="width:100%">  
  2.    <p><b>Custom Filters Example</b></p>  
  3.    <div>  
  4.       Name : <inputtype="text"ng-model="myName"/>  
  5.       <br/>  
  6.       Name in Upper Case : {{myName|touppercase}}  
  7.    </div>  
  8. </div>  
Output

Custom filter example

Custom Filter example with argument

In this example, custom filter has been created with parameter or argument. Here, I have created filter that is applied on array and returns the array which starts with specific character.

The following is my code for filter, controller and html.

Custom filter
  1. app.filter('startWith', function () {  
  2.    returnfunction (items, char) {  
  3.       var filtered = [];  
  4.       var match = newRegExp(char'i');  
  5.       for (vari = 0; i<items.length; i++) {  
  6.          var item = items[i];  
  7.          if (match.test(item.name.substring(0, 1))) {  
  8.             filtered.push(item);  
  9.          }  
  10.       }  
  11.       return filtered;  
  12.    };  
  13. });  
Controller
  1. app.controller("demoController", ['$scope', function ($scope) {  
  2. $scope.employeeArray = [  
  3.     { name: 'Tejas' },  
  4.     { name: 'Jignesh' },  
  5.     { name: 'Rakesh' },  
  6.     { name: 'Nirav' },  
  7.     { name: 'Jiten' },  
  8.     { name: 'Varun' },  
  9.     { name: 'Chirag' }  
  10.     ];  
  11.     $scope.empName = "j";  
  12. }]);  
Here, most important thing is where we were passing the argument. We passed  the argument with filter name separated by colon (:).

HTML
  1. <div ng-controller="demoController"style="width:100%">  
  2.    <p><b>Custom Filters Example</b></p>  
  3.    <p>Search Employee name start with: <inputtype="text"ng-model="empName"/></p>  
  4.    <ul>  
  5.       <ling-repeat="entry in employeeArray | startWith:empName ">{{entry.name}}</li>  
  6.    </ul>  
  7. </div>  
Output

Output

In the preceding example, filter takes only one argument. We can also create custom filter with multiple arguments.

Filter definition:
  1. app.filter('filterName', function () {  
  2.    return function (items, arg0, arg1, arg2, arg3) {  
  3.       // To do:  
  4.    };  
  5. });  
HTML:
  1. <ul>  
  2.    <li ng-repeat="entry in employeeArray | FilterName:arg0:arg1:arg2:arg3 ">{{entry.name}} </li>  
  3. </ul>  
Summary

Filters are a very powerful feature in AngularJS for transforming our data, so it easy to scale and reuse. We can also create custom filter base on our requirement.

Hope this will help you.


Similar Articles