AngularJs framework comes with a bunch of pre-defined filters to filter the application data as per our requirement. We have discussed all predefined filter in our early tutorials. Now it is the time to learn what is AngularJs Custom filter and how we can implement ?

What is Angularjs Custom Filter ?

Though we have a bunch of predefined filters in AngularJs, those may not be fulfill your application requirements, since all filters are comes with a specific requirement.

AngularJs given us to implement our own filters according to our business requirement.

Filters that we develop as per our customized requirements are called Custom Filters.

Example :

  • Display names starts with a specific character.
  • Filter only even numbers.
  • Filter only five multiples and etc..

How to create AngularJs Custom Filter :

We can create custom filter with angularJs module object reference.

AngularJs module object provides a method called filter() to create custom filter.

myApp.filter(“filterName”,function(){

// Required code..

})

AngularJs Custom Filter Example :

In the below example we are going to create custom filter for reverse of a string and string starts with a specific character.

[html]

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>AngularJs Custom Filter Example</title>
<script
    src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
    var myApp = angular.module("myApp",[]);
    
    myApp.controller("myController",function($scope){
        $scope.userName="Chandra Shekhar";
        $scope.courses = ["AngularJs","Java","Spring","Hibernate","Jquery","PHP","HTML"];
    })
    // creating custome filter to reverse of the string
    
    myApp.filter("reverse",function(){
        var fn_test = function(input){
            var ar = input.split(”);
            ar.reverse();
            var output = ar.join(”);
            return output;
        }
        return fn_test;
    });
    
    myApp.filter("startsWith",function(){
        var starts = function(input,option){
            var output=[];
            for(var i=0;i<input.length;i++){
                if(input[i].charAt(0) == option){
                    output.push(input[i]);
                }
            }
            return output;
        }
        return starts;
    })
    
    
    </script>
</head>
<body ng-app="myApp">
    <h1>AngularJs Custom Filter Example</h1>
    <div ng-controller="myController">
        User Name : {{userName | reverse}} <br>
        <br> <span> Filter Courses</span>
        <ol>
            <li ng-repeat="item in courses | startsWith:’J’">{{item}}</li>
        </ol>
    </div>
</body>
</html>
[/html]

Output :

[advanced_iframe securitykey=”85899c43cd5d45b9ec5729b5189d1961d89f90d9″ src=”http://nhk.e6a.mytemp.website/AngularJsExamples/Angular_Custom_Filter.html”]

Happy Learning 🙂