Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

Custom Filter in Angular JS

Posted in Angular JS

To register a filter you need to call the function angular.module().filter(). The first argument is the name of the filter. The second argument is the filter
factory function. If your filter has dependencies, you can list those as arguments in this function.

Syntax:

custom-filter-angularjs

The factory function returns an anonymous function i.e function with no name or so called as self executing function. This anonymous function accepts one argument which is input to the filter. Second argument is optional it depends on filter functionality. If you want to filter objects from an array then the second parameter can be an array.

Example:

The example metioned below is for a custom filter which reverse the input string.

   var myApp = angular.module("myApp", []);
   myApp.filter("reverse", function() {
    return function(input) {
        if (input !== undefined) {
            return split("").reverse().join("");
        }
    };
   });

   <div>{{ firstname | reverse  }}</div>

The above filter first checks for the input is undefined or not otherwise the filter throws an error on page load. It returns an revers of firstname using reverse and join javascript functions.