Custom Filters In Angular

This is the next article of AngularJS from basic to expert -day five. In this article, I am going to explain custom filter in angular js and how to create custom filter.

Introduction

This is the next article of my Angular series, continuing from Angular js from basic to expert -day five. In this article, I am going to explain custom filters in AngularJS and how to create a custom filter. Please find the previous article on built-in filters here.

AngularJS also provides the functionality of creating our own custom filter. We can create our own custom filters by registering the new filter factory function with our module. Please check the previous article for built-in filter in AngularJS here.

$filterProvider is responsible to create a filter function. $filterProvider is factory function and AngularJS internally use $filterProvider to create a filter function.

Creating custom filters is very easy. We only need to register a new filter factory method with our module. As we create the controller using angApp.controller(), the same way, we can create filter using angApp.filter().

  1. var angApp = angular.module('MyERPDemoApp', []);  
  2. angApp.filter('myNewFormat'function(data) { return data});  

AngularJS provides filter methods to create the custom filter. Internally, AngularJS uses the $filterProvider. This factory function returns a new filter function which takes an input value as the first parameter. Any other filter parameters are passed in as an additional parameter into the filter function.

Syntax
  1. var angApp = angular.module('MyERPDemoApp', []);  
  2.  angApp.filter('myNewFormat'function() {  
  3.  return function(datatofilter) {  
  4.  // work on your datatofilter  
  5.  return datatofilter;  
  6.  };  
  7.  });  
  8. HTML:  
  9. {{somedata | myNewFormat }}  

Let's create a custom filter to convert the first letter of the word in upper case. For example, if my name string is written like ‘arvind singh baghel’, it should be Arvind Singh Baghel. (Check comments in the code for details).

  1.  var angApp = angular.module("MyERPDemoApp", []);  
  2.        // creating custom filter to convert first letter of word in upper case  
  3.        // e.g input arvind singh baghel, output: Arvind Singh Baghel  
  4.       // creating custome filter using filter function named myNewFormat  
  5.      angApp.filter('myNewFormat'function()   
  6.      return function(datatofilter) { // datatofilter is input value  
  7.      var res = datatofilter.split(" "); // split input by space in array     
  8.     // e.g input is 'arvind singh' we get 2 item in our res array  
  9.     // loop through the item in array and convert first letter to upper case   
  10.   
  11.      for(var i=0; i < res.length;i++){  
  12.       res[i]= res[i].substr(0,1).toUpperCase()+res[i].substr(1);  
  13.      }  
  14.      // join the array items in single string  
  15.      var fullstring= res.join(" ");  
  16.      return fullstring;  
  17.     };  
  18. });  

In the below example, I will cover all the built-in filters and create a custom filter which will format the first character of every word in upper case. The following details are explained using the comments inside the code.

  1. <!DOCTYPE html>  
  2. <head>  
  3. <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js">  
  4. </script>  
  5. <script>  
  6.      var angApp = angular.module("MyERPDemoApp", []);  
  7.        
  8.      // creating custom filter to convert first letter of word in upper case
  9.      // e.g input arvind singh baghel, output: Arvind Singh Baghel
  10.      // creating custome filter using filter function named myNewFormat
  11.      angApp.filter('myNewFormat', function() {  
  12.      return function(datatofilter) {   // datatofilter is input value
  13.      var res = datatofilter.split(" ");   // split input by space in array
  14.      // e.g input is 'arvind singh' we get 2 item in our res array
  15.      // loop through the item in array and convert first letter to upper case
  16.      for(var i=0; i<res.length;i++){  
  17.       res[i]= res[i].substr(0,1).toUpperCase()+res[i].substr(1);  
  18.      }  
  19.      // join the array items in single string using join and return
  20.      return res.join(" ");  
  21.     };  
  22.   });  
  23.     
  24.     //Creating controller with name UserController.  
  25.     angApp.controller('UserController', function($scope) {  
  26.     $scope.welcomenote="Welcome to Angular JS world";  
  27.     $scope.title="Angular JS filter example";  
  28.     $scope.PersonNames = [  
  29.         {name:'arvind singh baghel',DOB:new Date(),country:'India', fee: 100},  
  30.         {name:'tom cruis',DOB:new Date(),country:'united States',fee:null} ,   
  31.         {name:'denial crg',DOB:new Date(),country:'United kingdom',fee:null},  
  32.         {name:'ronaldo',DOB:new Date(),country:'brazil',fee:1000} ,           
  33.         ];  
  34.       
  35.     $scope.orderByThis = function(data) {  
  36.     $scope.customOrderBy = data;        
  37.     }     

  38.    });  
  39.   
  40. </script>  
  41. </head>  
  42. <body ng-app="MyERPDemoApp" ng-controller="UserController">  
  43.   
  44. <!-- uppercase filter -->  
  45. Uppercase Filter : <span ng-bind="welcomenote | uppercase">  </span></br>  
  46. <!-- lowercase filter -->  
  47. lowercase filter : <span> {{ title | lowercase}} </span></br>  
  48.   
  49. <p>Enter Name To Filter : <input type="text" ng-model="name"><p>  
  50. <table border="1" >  
  51. <tr > <td ng-click="orderByThis('name')">Name</td> <td ng-click="orderByThis('DOB')">DOB</td> <td ng-click="orderByThis('country')">Country</td> <td ng-click="orderByThis('fee')">Fee</td>  
  52. </tr>  
  53.        <!-- filter and orderBy filter-->  
  54.     <tr ng-repeat="person in PersonNames | filter:name | orderBy:customOrderBy">  
  55.          <!-- customer myNewFormat filter -->  
  56.         <td>{{person.name | myNewFormat}}</td>  
  57.          <!-- date filter -->  
  58.          <td>{{person.DOB | date:'dd/MM/yyyy'}}</td>  
  59.         <td>{{person.country}}</td>  
  60.          <!-- currency filter -->  
  61.          <td>{{person.fee | currency}}</td>  
  62.     </tr>  
  63. </table>  
  64. </body>  
  65. </html>  

Run this above sample and see the output.