Filters In AngularJS

Introduction


Filters are used to modify the data and can be clubbed in expression or directives using a pipe character. A filter formats the value of an expression for display to the user. They can be used in view templates, controllers, or services,  and we can easily create our own filter.

Syntax

Filter can be applied as in the following syntax:

{{ expression | filter }}

We can also apply multiple filter as in the following syntax:

{{ expression | filter1 | filter2 |...}}

Filter may be applied that have some arguments:

{{ expression | filter:argument1:argument2:...}}

Below table show the list of filters that are generally used:

Filter Description
Uppercase Converts a text to upper case text.
Lowercase Converts a text to lower case text.
Currency Formats text in a currency format.
Filter Filter the array to a subset of it based on provided criteria.
Orderby Orders the array based on provided criteria.

Let us take some examples:

Example 1

  1. <body ng-app="">  
  2.     <div id="div1"> <span>Enter Name:</span>  
  3.         <input id="inp1" type="text" ng-model="EmpName" /><br/> <span>Salary Per Day:</span>  
  4.         <input id="inp2" type="text" ng-model="salaryDay" /><br/> <span>Total Working Day:</span>  
  5.         <input id="inp3" type="text" ng-model="workingDay" /><br/>  
  6.         <p>Hello! {{EmpName|uppercase}} Your Salary is {{(salaryDay*workingDay)|currency:"₹"}}</p>  
  7.     </div>  
Output

see Output

In this example we use the “uppercase” and “currency” filter, we define the Indian rupees symbol for currency.

Example 2
  1. <html>  
  2.   
  3.     <head>  
  4.         <title>Angular JS Controller</title>  
  5.         <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">  
  6.             </script>  
  7.             <script>  
  8.             var mainApp = angular.module("mainApp", []);  
  9.             mainApp.controller('State', function ($scope)  
  10.             {  
  11.                 $scope.array = [  
  12.                 {  
  13.                     name: 'Andra Pradesh',  
  14.                     capital: 'Hyderabad'  
  15.                 },  
  16.                 {  
  17.                     name: 'Arunachal Pradesh',  
  18.                     capital: 'Itangar'  
  19.                 },  
  20.                 {  
  21.                     name: "Bihar",  
  22.                     capital: "Patna"  
  23.                 },  
  24.                 {  
  25.                     name: "Chhattisgarh",  
  26.                     capital: "Raipur"  
  27.                 },  
  28.                 {  
  29.                     name: "Goa",  
  30.                     capital: "Panaji"  
  31.                 },  
  32.                 {  
  33.                     name: "Haryana",  
  34.                     capital: "Chandigarh"  
  35.                 },  
  36.                 {  
  37.                     name: "Jammu and Kashmir",  
  38.                     capital: "Srinagar and Jammu"  
  39.                 },  
  40.                 {  
  41.                     name: "Kerala",  
  42.                     capital: "Thiruvananthapuram"  
  43.                 },  
  44.                 {  
  45.                     name: "Mizoram",  
  46.                     capital: "Aizawi"  
  47.                 },  
  48.                 {  
  49.                     name: "Rajasthan",  
  50.                     capital: "Jaipur"  
  51.                 },  
  52.                 {  
  53.                     name: "Sikkim",  
  54.                     capital: "Gangtok"  
  55.                 },  
  56.                 {  
  57.                     name: "Uttaranchal",  
  58.                     capital: "Dehradun"  
  59.                 },  
  60.                 {  
  61.                     name: "West Bengal",  
  62.                     capital: "Kolkata"  
  63.                 }]  
  64.             })  
  65.             </script>  
  66.             <style>  
  67.             #div1 {  
  68.                 height800px;  
  69.                 background-color: crimson;  
  70.                 font-size24px  
  71.             }  
  72.               
  73.             span {  
  74.                 margin-left100px;  
  75.                 margin-top50px;  
  76.             }  
  77.               
  78.             #inp1 {  
  79.                 margin-left80px;  
  80.                 margin-top20px;  
  81.             }  
  82.               
  83.             table,  
  84.             th,  
  85.             td {  
  86.                 border-collapsecollapse;  
  87.                 padding5px;  
  88.             }  
  89.               
  90.             tabletr:nth-child(odd) {  
  91.                 background-color#82F2E5;  
  92.                 font-familyVerdana;  
  93.             }  
  94.               
  95.             tabletr:nth-child(even) {  
  96.                 background-colorblue;  
  97.                 colorwhite;  
  98.                 font-familyArial;  
  99.             }  
  100.               
  101.             #div1 {  
  102.                 margin-left150px;  
  103.                 margin-top20px  
  104.             }  
  105.             </style>  
  106.     </head>  
  107.     <body ng-app="mainApp">  
  108.         <div id="div1" ng-controller="State"> <span>Enter Name:</span>  
  109.             <input id="inp1" type="text" ng-model="StateName" /><br/>  
  110.             <div id="div1">  
  111.                 <table>  
  112.                     <tr>  
  113.                         <th>State</th>  
  114.                         <th>Capital</th>  
  115.                     </tr>  
  116.                     <trng-repeat="obj in array | filter:StateName | orderBy:'name'">  
  117.                         <td>{{obj.name}}</td>  
  118.                         <td>{{obj.capital}}</td>  
  119.                         </tr>  
  120.                 </table>  
  121.             </div>  
  122.         </div>  
  123.     </body>  
  124.   
  125. </html>  
Output

Web page after page load.

page after page load

In this example we use the filter and orderby filter. The “filter” filter is used to display only required information as per user input or predefine manner.

orderby filter

enter detail

Use Filter In Controller


We can also use the filters in controllers. For this we need to inject a dependency with the name <filterName>Filter into our controller. For example if we want to use the number filter in controllers then we need to inject dependency "numberFilter". The injected argument is a function that takes the value to format as first argument, and filter parameters starting with the second argument.

Example
  1. <html>  
  2.   
  3.     <head>  
  4.         <title>Angular JS Controller</title>  
  5.         <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">  
  6.             </script>  
  7.             <script src="angular.min.js">  
  8.                 </script>  
  9.                 <script>  
  10.                 var mainApp = angular.module("mainApp", []);  
  11.                 mainApp.controller('Employee', function ($scope, filterFilter)  
  12.                 {  
  13.                     $scope.filter_ = 'p',  
  14.                         $scope.array = [  
  15.                         {  
  16.                             name: 'Pankaj'  
  17.                         },  
  18.                         {  
  19.                             name: 'Sandeep'  
  20.                         },  
  21.                         {  
  22.                             name: 'Neeraj'  
  23.                         },  
  24.                         {  
  25.                             name: 'Sanjeev'  
  26.                         },  
  27.                         {  
  28.                             name: 'Rahul'  
  29.                         },  
  30.                         {  
  31.                             name: 'Priya'  
  32.                         }],  
  33.                         $scope.sort = function ()  
  34.                         {  
  35.                             varobj = "";  
  36.                             $scope.filteredArray = filterFilter($scope.array, $scope.filter_);  
  37.                             for (obj_ in $scope.filteredArray)  
  38.                             {  
  39.                                 obj += $scope.filteredArray[obj_].name + ",";  
  40.                             }  
  41.                             returnobj.substring(0, obj.length - 1);  
  42.                         }  
  43.                 })  
  44.                 </script>  
  45.                 <style>  
  46.                 #div1 {  
  47.                     height: 600px;  
  48.                     width: 400x;  
  49.                     background-color: crimson;  
  50.                     font-size: 24px  
  51.                 }  
  52.                   
  53.                 span {  
  54.                     margin-left: 100px;  
  55.                     margin-top: 50px;  
  56.                 }  
  57.                   
  58.                 input {  
  59.                     margin-left: 20px;  
  60.                     margin-top: 20px;  
  61.                 }  
  62.                  
  63.                 #li1 {  
  64.                     color: #B4E825  
  65.                 }  
  66.                 </style>  
  67.     </head>  
  68.     <body ng-app="mainApp">  
  69.         <div id="div1" ng-controller="Employee"> <span>Enter Name:</span>  
  70.             <input type="text" ng-model="filter_" /><br/>  
  71.             <ul>  
  72.                 <li id="li1">{{sort()}}</li>  
  73.             </ul>  
  74.             <ul>  
  75.                 <li ng-repeat="entry in array">{{entry.name}}</li>  
  76.             </ul>  
  77.         </div>  
  78.     </body>  
  79.   
  80. </html>  
Output

run program

filter
  1. function ($scope, filterFilter)  
  2. $scope.filteredArray = filterFilter($scope.array, $scope.filter_);  
In above example we define a “filterFilter” filter and this filter used to filter the data from “filteredArray” array as per value of “filter_” .

Create Custom Filter


We can also write our own custom filter. Writing your own filter is very easy, just register a new filter factory function with your module. This uses the "filterProvider" internally. By default the new filter function takes the input value as the first argument and the factory function will return the new filter. The filter function should be a pure function, that means it should be stateless and idempotent. The returned functions in filter are getting invoked every time when AngularJS call the filter. It means, their is a two-way binding for a filter.

Syntax

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


Example
  1. <html>  
  2.   
  3.     <head>  
  4.         <title>Angular JS Controller</title>  
  5.         <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">  
  6.             </script>  
  7.             <script src="angular.min.js">  
  8.                 </script>  
  9.                 <script>  
  10.                 var mainApp = angular.module("mainApp", []);  
  11.                 mainApp.filter('Reverse', function ()  
  12.                 {  
  13.                     return function(item, AltenaterCase)  
  14.                     {  
  15.                         var obj = "";  
  16.                         if (AltenaterCase)  
  17.                         {  
  18.                             for (i = item.length - 1; i >= 0; i--)  
  19.                             {  
  20.                                 if (i % 2 == 0)  
  21.                                 {  
  22.                                     obj += item[i].toUpperCase();  
  23.                                 }  
  24.                                 else  
  25.                                 {  
  26.                                     obj += item[i];  
  27.                                 }  
  28.                             }  
  29.                         }  
  30.                         else  
  31.                         {  
  32.                             for (i = item.length - 1; i >= 0; i--)  
  33.                             {  
  34.                                 obj += item[i];  
  35.                             }  
  36.                         }  
  37.                         return obj;  
  38.                     }  
  39.                 })  
  40.                 mainApp.controller('Employee', function ($scope, filterFilter)  
  41.                 {  
  42.                     $scope.filter_ = 'p',  
  43.                         $scope.array = [  
  44.                         {  
  45.                             name: 'Pankaj'  
  46.                         },  
  47.                         {  
  48.                             name: 'Sandeep'  
  49.                         },  
  50.                         {  
  51.                             name: 'Neeraj'  
  52.                         },  
  53.                         {  
  54.                             name: 'Sanjeev'  
  55.                         },  
  56.                         {  
  57.                             name: 'Rahul'  
  58.                         },  
  59.                         {  
  60.                             name: 'Priya'  
  61.                         }],  
  62.                         $scope.sort = function ()  
  63.                         {  
  64.                             var obj = "";  
  65.                             $scope.filteredArray = filterFilter($scope.array, $scope.filter_);  
  66.                             for (obj_ in $scope.filteredArray)  
  67.                             {  
  68.                                 obj += $scope.filteredArray[obj_].name + ",";  
  69.                             }  
  70.                             return obj.substring(0, obj.length - 1);  
  71.                         }  
  72.                 })  
  73.                 </script>  
  74.                 <style>  
  75.                 #div1 {  
  76.                     height600px;  
  77.                     width400x;  
  78.                     background-color: crimson;  
  79.                     font-size24px  
  80.                 }  
  81.                   
  82.                 span {  
  83.                     margin-left100px;  
  84.                     margin-top50px;  
  85.                 }  
  86.                   
  87.                 input {  
  88.                     margin-left20px;  
  89.                     margin-top20px;  
  90.                 }  
  91.                   
  92.                 #li1 {  
  93.                     color#B4E825  
  94.                 }  
  95.                   
  96.                 #li2 {  
  97.                     color#1DE0B9  
  98.                 }  
  99.                   
  100.                 #li3 {  
  101.                     color#20E01D  
  102.                 }  
  103.                 </style>  
  104.     </head>  
  105.     <body ng-app="mainApp">  
  106.         <div id="div1" ng-controller="Employee"> <span>Enter Name:</span>  
  107.             <input type="text" ng-model="filter_" /><br/>  
  108.             <ul>  
  109.                 <li id="li1">List Without reverse: {{sort()}}</li>  
  110.                     <li id="li2">Reverse List Without AltenaterCase: {{sort()|Reverse}}</li>  
  111.                         <li id="li3">Reverse List With AltenaterCase: {{sort()|Reverse:true}}</li>  
  112.             </ul>  
  113.             <ul>  
  114.                 <ling-repeat="entry in array">{{entry.name}}</li>  
  115.             </ul>  
  116.         </div>  
  117.     </body>  
  118.   
  119. </html>  
Output

Custom Filter in AngularJS

Custom Filter in AngularJS

In above example we created a custom filter that is “Reverse.” This function take two parameters, first parameter “item” contains data and the second parameter “AltenaterCase” contains information whether alternation of case (uppercase and lowercase) will perform or not. “Reverse” filter reverses and returns this string to expression.

Custom Filter in AngularJS

We used this filter two times in the above code. At first time “sort()|Reverse” we retrieved a reverse string and at the second time “sort()|Reverse:true” we retrieved a string that is in reverse order and case of letter in alternate order.

Custom Filter in AngularJS

Summary


Filters are very powerful features in AngularJS for transforming our data and it is easy to scale and reuse. We can use a filter either in directory or in controller and we can also create custom filter based on our requirement. 


Similar Articles