Learn How to Create Custom Filter in AngularJS

Posted By : Rajat khurana | 09-Apr-2017

Today we will develop a custom filter in angularjs. There are various built in filter available in angular like uppercase, date, currency etc which are easy to use. We will build a filter that manuplate strings and number. To declare a filter we need to pass two parameter in app filter, first one is filter name and second is function that will return another function that does the main work for filter. In return function, first parameter is data on which we will work on. Remember multiple parameter also can be pass into it.
 

Here is filter.html file where filter is apply on the basis of its name. 
 


<html>
<head>
<title>
Angular Learning
</title>
</head>
<body ng-app="app">
<div ng-controller="MainController">
<input type="text" ng-model="mydata.val">
<h2>{{ mydata.val | uppercase }}</h2>
<div>
<h3>Creating Custom Based on Array Deletion</h3>
<div ng-repeat = "user in filter.arr | reducearray ">
 {{ user  }}
</div>
</div>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js" ></script>
<script type="text/javascript" src="app.js" ></script>
</body>
</html>

Here is app.js file where controller is defined .
 

var app = angular.module('app',[]);

app.controller('MainController',function($scope){

$scope.filter = { arr: [ {name:"ghgafgsggjgsyh",age:33 },{name:"Deffsfsdfrfk",age:42 },{name:"jjfghfhgfhggg",age:11 }, ]};
 
$scope.mydata = { val: "Hello"};
  

});

app.filter('reducearray',function(){

return function(input,length)
  {
    var filteredata = [];

    if(!length)
    {
      length = 20;
    }
    for(var i=0; i<input.length; i++)
    {
        var value = input[i];
         if(value.age > length)
         {

         filteredata.push(input[i]);
         }
    }

  return filteredata;
  }

   })


Here we create a custom filter reducearray in app.js which check age parameter of data and on basis of condition data is displayed on browser. An array i.e filterdata is return  form custom filter and see in html there is loop i.e ng-repeat and reducearray filter is applied on it. Also we use inbuilt feature which is show abpove in html file i.e uppercase. 
 

THANKS

About Author

Author Image
Rajat khurana

Rajat is a bright Javascript Developer, he has good knowledge of HTML, WordPress, NodeJs, Core Java, Javascript, Jquery. Apart from this he loves to play Badminton and PC Gaming.

Request for Proposal

Name is required

Comment is required

Sending message..