EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials AngularJS Tutorial AngularJS Custom Filter
Secondary Sidebar
AngularJS Tutorial
  • AngularJS Basic and Advance
    • What is AngularJS
    • Career In AngularJS
    • Uses of Angular JS
    • AngularJS Architecture
    • Angular JS Application
    • AngularJS Application
    • AngularJS Filter Array
    • AngularJS ng-style
    • AngularJs ng init
    • AngularJs ng-repeat
    • AngularJs ng-change
    • AngularJs ng-options
    • AngularJs expressions
    • AngularJs onclick
    • AngularJS ng-show
    • AngularJs ng-include
    • Scope in AngularJS
    • AngularJS ng-if
    • AngularJS Number Filter
    • AngularJS Date Filter
    • AngularJS ng-class
    • AngularJS ng-model
    • AngularJS ng-disabled
    • AngularJS Custom Filter
    • AngularJS Validation
    • AngularJS Filters
    • Controllers in AngularJS
    • AngularJS Animations
    • AngularJS Services
    • AngularJS Events
    • AngularJS Versions
    • AngularJS Directives
    • AngularJS Unit Testing
    • AngularJS with Bootstrap
    • AngularJS UI Bootstrap
    • AngularJS Routing Example
  • Interview Question
    • Angular JS Interview Questions

AngularJS Custom Filter

By Priya PedamkarPriya Pedamkar

AngularJS Custom Filter

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

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,883 ratings)

.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

  1. Create an AngularJS application.
  2. Use (dot) .filter API provide by AngularJS framework to add.
  3. Pass a filter name and filter function to custom.
  4. 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:

AngularJS Custom Filter-1.1

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:

AngularJS Custom Filter-1.2

 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:

Output-1.3

  • 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:

Output-1.4

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

This is a guide to AngularJS Custom Filter. Here we discuss the Introduction and steps to create a custom filter along with different examples and its code implementation. You may also have a look at the following articles to learn more –

  1. AngularJS Validation
  2. AngularJS Filters
  3. AngularJS Services
  4. AngularJS Currency Filter
Popular Course in this category
Angular JS Training Program (9 Courses, 7 Projects)
  9 Online Courses |  7 Hands-on Projects |  64+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more