AngularJS custom filter

Using custom filter

Till now we have seen built-in filters that provide important functionality such as formatting dates, currencies, limiting the number of items displayed, uppercase, lowercase etc. Many times these predefined filters are not enough. In AngularJS you can create custom filter according to your need.

Suppose that you want to create a custom filter and its name is reverseString.

There is a filter() function for each module in angularJS that takes two parameter. The first parameter is the name of the filter and second parameter is a function that will return another function that does the actual work of the filter.

We must pass a single parameter in second function. The second parameter is the data which we will work on.

Example: Custom filter in AngularJS

<!DOCTYPE html>
<html>
     <head>
          <script src="Scripts/angular.min.js"></script>
     </head>
     <body style="font-family:Arial; font-size:medium; color:darkblue">
          <div ng-app="myModule">
               <h3>Custom filter in AngularJS</h3>
               <br/>
               Enter the text : <input type="text" ng-model="inputText"/>
               <br/><br/>
               Reverse string :{{inputText|reverseString}}
          </div>
          <script>
               //Create a module
               var myApp = angular.module("myModule", []);
               //Create a custom Filter name reverseString.
               myApp.filter("reverseString", function ()
               {
                    //Defining the filter function
                    returnfunction (input)
                    {
                         var result = "";
                         input = input || "";
                         for (vari = 0; i<input.length; i++)
                         {
                              result = input.charAt(i) + result;
                         }
                         return result;
                    };
               });
          </script>
     </body>
</html>


Output:
custom filter