AngularJS Filters
In AngularJS, filters are used to format data displayed to the user. They can be applied to expressions in templates, controllers, services, or directives to transform the output before it is rendered. Filters are particularly useful for formatting dates, numbers, strings, and other types of data.
Syntax –
{{ expression | filterName:parameter1:parameter2:... }}
Where:
- expression is the value to be filtered.
- filterName is the name of the filter function.
- parameter1, parameter2, etc., are optional parameters that can be passed to the filter function.
Here are some built-in filters,
- currency Format a number to a currency format.
- date Format a date to a specified format.
- filter Select a subset of items from an array.
- json Format an object to a JSON string.
- limitTo Limits an array/string, into a specified number of elements/characters.
- lowercase Format a string to lower case.
- number Format a number to a string.
- orderBy Orders an array by an expression.
- uppercase Format a string to upper case.
currency filter formats a number to a currency format. By default, the locale currency format is used.
Syntax
{{ number | currency : symbol : fractionsize }}
Example -
<div data-ng-init="price = 500">
<p>Price = {{ price | currency }}</p>
<p>Price = {{ price | currency : "INR" }}</p>
<p>Price = {{ price | currency : "INR " }}</p>
<p>Price = {{ price | currency : "USD " }}</p>
</div>
date filter formats a date to a specified format. The date can be a date object, milliseconds, or a datetime string like "2016-01-05T09:05:05.035Z". By default, the format is "MMM d, y" (Jan 5, 2016).
Syntax
{{ date | date : format : timezone }}
Example -
<div data-ng-init="price = 500; today = '2016-01-05T09:05:05.035Z'">
<p>Date = {{ today | date }}</p>
<p>Date = {{ today | date : yyyy }}</p>
<p>Date = {{ today | date : "dd.MM.y" }}</p>
<p>Date = {{ today | date : "fullDate" }}</p>
<p>Date = {{ today | date : "'today is ' MMMM d, y" }}</p>
</div>
filter filter allows us to filter an array, and return an array containing only the matching items. This filter can only be used for arrays.
Syntax
{{ arrayexpression | filter : expression : comparator }}
Example -
<div data-ng-init="subjects=['hindi', 'english', 'math', 'science', 'social science']">
<ul>
<li data-ng-repeat="subject in subjects | filter:'sc'">{{subject}}</li>
</ul>
</div>
lowercase filter converts a string to lowercase letters.
Syntax
{{ string | lowercase }}
uppercase filter converts a string to uppercase letters.
Syntax
{{ string | uppercase}}
Example -
<div data-ng-init="subjects=['hindi', 'english', 'math', 'science', 'social science']">
<p>Filter text with {{"LowerCase" | lowercase}} and {{"UpperCase" | uppercase}}</p>
<ul>
<li data-ng-repeat="subject in subjects | filter:'sc'">
<span>{{ subject | lowercase }}</span> ++ <span>{{ subject | uppercase }}</span>
</li>
</ul>
</div>
number filter formats a number to a string.
Syntax
{{ string | number : fractionsize}}
Example -
<div data-ng-init="weight = 99">
<h1>{{weight | number}}</h1>
<h1>{{weight | number}} kg</h1>
<h1>{{weight | number : 3}} kg</h1>
</div>
orderBy filter allows us to sort an array. By default, strings are sorted alphabetically, and numbers are sorted numerically.
Syntax
{{ array | orderBy : expression : reverse }}
Example -
<div data-ng-init="numbers=[5, 3, 8, 1, 9, 2]">
<ul>
<li data-ng-repeat="number in numbers | orderBy: ''">
{{ number }}
</li>
</ul>
</div>
How to create a custom filter in AngularJS,
In AngularJS, filters are used to format data displayed to the user. You can create custom filters to tailor the data presentation according to your needs. Here's an example of how you can create a custom filter in AngularJS:
Example -
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap demo</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<div data-ng-app="customFilterApp" class="container" ng-controller="MainController">
<div class="" data-ng-init="numbers = [1, 2,3, 7, 8, 15, 42, 65, 25, 12, 36, 74, 85, 96, 49]; text='Odd'">
<p><span class="fw-bold text-capitalize">{{text}}</span> list</p>
<ul>
<li class="" data-ng-repeat="item in numbers | numberType:text" >{{item}}</li>
</ul>
</div>
<div>
<h1>Filter Here</h1>
<!-- Create a form for filter data -->
<form class="row g-3">
<div class="col-12">
<label class="form-label fw-bold">Text</label>
<!-- create input box for send and recive user input to controller -->
<input type="text" data-ng-model="searchText" placeholder="Search..." class="form-control" autofocus="true" />
<!-- show no of count filterd count -->
<div id="emailHelp" class="form-text fw-bold">{{(items | customFilter:searchText).length}} data
found.</div>
</div>
<!-- check count is >0 then show if condisin is fail then this div is hide-->
<div class="col-12" data-ng-show="(items | customFilter:searchText).length > 0">
<p class="fw-bold mt-3">Filtered data.</p>
<!-- iterate the items -->
<ul >
<li data-ng-repeat="item in items | customFilter:searchText" data-ng-bind="item" data-ng-class="(searchText ? 'text-warning fw-bold' : '')"></li>
</ul>
</div>
</form>
</div>
</div>
<script>
angular.module('customFilterApp', [])
.controller('MainController', function ($scope) {
$scope.items = ["Apple","Apricot","Avocado","Banana","Bilberry","Blackberry","Blackcurrant","Blueberry","Boysenberry","Currant","Cherry","Cherimoya","Cloudberry","Coconut","Cranberry","Custard apple","Damson","Date","Dragonfruit","Durian","Elderberry","Feijoa","Fig","Goji berry","Gooseberry","Grape","Raisin","Grapefruit","Guava"];
})
.filter('reverse', function() { /*This is reverse filter it take a string and return the reverse of string */
return function(input) {
if (!input) return '';
return input.split('').reverse().join('');
};
})
.filter('numberType', function() { /* this is numberType custom filter it take an array of interger and numbertype like ['even', 'odd', 'prime'], It return value according to your choice. */
return function(array, text) {
var filteredArray = [];
if (!text || !['even', 'odd', 'prime'].map(function(item) { return item.toLowerCase(); }).includes(text.toLowerCase())) {
return array;
}
switch (text.toLowerCase()) {
case 'even':
filteredArray = array.filter(function(item) {
return item % 2 === 0;
});
break;
case 'odd':
filteredArray = array.filter(function(item) {
return item % 2 !== 0;
});
break;
case 'prime':
filteredArray = array.filter(function(item) {
if (item < 2) return false;
for (var i = 2; i <= Math.sqrt(item); i++) {
if (item % i === 0) return false;
}
return true;
});
break;
}
return filteredArray;
};
})
.filter('customFilter', function () {
return function (array, text) {
if (!text)
return array;
var filtered = [];
angular.forEach(array, function (item) {
if (item.toLowerCase().indexOf(text.toLowerCase()) !== -1) {
filtered.push(item);
}
});
return filtered;
};
});
</script>
</body>
</html>
Thank you,
I hope you are enjoying this article.
Leave Comment