Updated March 28, 2023
Introduction to AngularJS Custom Filter
In AngularJS filters are used to modify or update the data before rendering the data on view or UI. Filters are clubbed in expression or directives using pipe (|) symbol. There are a lot of built-in filters provided by AngularJS framework, and we can directly use them in our project (code) as per our requirement, some of the examples of built-in filters are uppercase, lowercase, currency, orderby, etc. These built-in filters cover a lot of common use cases that include formatting of dates, currencies, strings, etc. but at times these common filters might not work for our requirements, in such cases, we can create our own custom filters in AngularJS applications.
Custom Filters in AngularJS
At times we may need custom filters in our application. AngularJS framework exposes us to an API for creating custom filters. We can create a custom filter by using dot(.) filter (dot) to angular Module. The syntax for creating a custom filter
.filter('filterName', function ( ) {} )
Few Example of Custom Filter:
Some example requirement that can be solved by creating custom filters could be:
- Prefix or suffix any String to the input.
- Filter even/odd numbers from an array of.
- Filter based on any custom logic e. multiple of five etc.
- Reverse a string or.
Steps to Create a Custom Filter
- Create an AngularJS application.
- Use (dot) .filter API provide by AngularJS framework to add.
- Pass a filter name and filter function to custom.
- Write logic for transforming the input to output in return.
Code:
/*Create myApp Angular module */
var myApp = angular.module('myApp' , [ ] );
/* As mentioned above, AngularJS exposes filter API to create custom filters, below code snippet uses filter API to create custom filter, the first parameter is the name of the filter that is firstFilter and second parameter is name of function, second parameter the function returns a function in itself, this is the place where we are supposed to write transformation logic of input to output. */
myApp.filter( 'firstFilter' , function ( ) {
/*return function returned by filter containing logic for transformation*/
return function (input, parameter_1, parameter_2) { let transformedOutput;
/* transform input here, function receives input of filter as input or first parameter */
input
/* Here we can write our custom logic to transform input to output, write logic here */
return transformedOutput;
} } ) ;
Examples of AngularJS Custom Filter
Below is the skeleton of an AngularJS filter:
myApp.filter('filterNameHere', function () { return function () {
return;
} ;
} ) ;
Example #1
This is an example code it creates a custom filter to create a filter of an array of people and returns an array with more than 60 years of age (senior citizens). Let’s assume an input array of individuals with name and age and we want to have a global filter in our module to filter array based on the age of the person and mark as senior citizens.
Code:
persons = [ {
name: 'Andrew John', age:25
} ,
{
name: 'Will Smith', age:60
},
{
name: 'Mark Taylor', age:35
} , {
name: 'Alice teams', age:65
} ,
{
name: 'Todd ran',
age:75
} ] ;
var myApp = angular.module('myApp', []);
myApp.filter('seniorCitizenFilter', function () { return function (personsArray) {
let seniorCitizen = personsArray.filter((person) => { return person.age>59;
})
return seniorCitizen;
} ;
} ) ;
Use of filter in Template:
<ul>
<li ng-repeat="seniorCitizen in persons | seniorCitizenFilter"> Name : {{ seniorCitizen .name}} , Age: {{ seniorCitizen .age}}
</li>
</ul>
Output:
This is an output of our first custom filter, this filter accepts an array of persons having and each person is an object having an age property, seniorCitizenFilter checks each item of the array and checks the age of each item if it is greater than 59 and returns a new array.
Example #2
This custom filter accepts input and a single character string in Javascript and returns if the string starts with the provided character. This code uses regex to check if the string starts with the provided character.
Code:
var myApp = angular.module( 'myApp', [ ] ); myApp.controller('PersonController', function () {
this.personName = [ { name: 'Andrew'
} , {
name: 'Mill'
} , {
name: 'Mar Hut'
} , {
name: 'Alice Mood'
}, {
name: 'Mask Tor'
} ] ;
} ) ;
myApp.filter('startsWithChar', function () { return function (items, char) {
let filteredArray = [];
for (let i = 0; i < items.length; i++) { let item = items[ I ];
if (/char/i.test(item.name.substring ( 0, 1) ) ) { filteredArray.push(item);
}
}
return filteredArray;
} ;
} ) ;
HTML Code:
<div ng-app="myApp">
<div ng-controller="PersonController as person">
<ul>
<li ng-repeat="person in person. personName | startsWithChar :a">
{{person.name}}
</li>
</ul>
</div>
</div>
Output:
In the output, we can see filtered names those start with character “A”, <li> tag runs twice and prints or renders two names on UI. The above two custom filters were actually filtering the input data or Array and giving us a new array, but in AngularJS we can also have filters that transform the data and provide us new data, an example of this could be custom currency filter.
Example #3
Code:
var myApp = angular.module('myApp', []); myApp.controller('myController', function ($scope) {
$scope.amount = 1000.33;
});
app.filter('INRFormatter', function () { return function (input) {
if (! isNaN(input)) {
let currencySymbol = '₹';
let result = input.toString().split('.');
let lastThree = result[0].substring(result[0].length - 3);
let otherNum = result[0].substring(0, result[0].length - 3); if (otherNum != '')
lastThree = ',' + lastThree;
let output = otherNum.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree;
if (result.length > 1) { output += "." + result[1];
}
}
});
return currencySymbol + output;
}
- 1st Usage in Template
<! DOCTYPE html>
<html ng-app="app">
<head>
</head>
<body ng-controller="myController">
Input: <input type="text" ng-model="amount">
<h3>{{amount | INRFormatter}}</h3>
</body>
</html>
Output:
- 2nd Usage in Template
<! DOCTYPE html>
<html ng-app="app">
<head>
</head>
<body ng-controller="testController">
Input: <input type="text" ng-model="amount">
<h3>{{344.00 | INRFormatter}}</h3>
</body>
</html>
Output:
Conclusion
AngularJS is a very powerful web development framework, and it provides us a way to transform and filter the data on UI itself through filters, we are provided with some built-in filters by frameworks and if required frameworks expose .filter API to create custom filters per our requirements.
Recommended Articles
We hope that this EDUCBA information on “AngularJS Custom Filter” was beneficial to you. You can view EDUCBA’s recommended articles for more information.