Filters in AngularJS allow data transformation before displaying it in the view. By chaining multiple filters, we can apply multiple transformations sequentially, making data formatting more powerful and flexible.
For example, you can format text, apply search filters, control decimal places, and modify data dynamically by chaining multiple filters together.
1. Syntax of Chaining Filters
Filters are chained using the pipe (|
) operator:
{{ expression | filter1 | filter2 | filter3 }}
Each filter processes the output of the previous one.
2. Example: Chaining Text Formatting Filters
Let’s combine uppercase
, reverse
, and a custom removeSpaces
filter.
Step 1: Define Custom Filter (removeSpaces)
angular.module('myApp', [])
.filter('removeSpaces', function() {
return function(input) {
if (!input) return '';
return input.replace(/\s+/g, '');
};
});
Step 2: Apply Multiple Filters in HTML
<p>{{ "hello world" | uppercase | reverse | removeSpaces }}</p>
Processing Steps
uppercase
:"HELLO WORLD"
reverse
:"DLROW OLLEH"
removeSpaces
:"DLROWOLLEH"
Output
DLROWOLLEH
3. Example: Formatting Currency and Limiting Decimal Places
Use Case
- Convert number to currency format.
- Limit decimal places.
- Convert currency to uppercase.
<p>{{ 1234.56789 | currency | uppercase | limitTo:8 }}</p>
Processing Steps
currency
:$1,234.57
uppercase
:$1,234.57
limitTo:8
:$1,234.5
Output
$1,234.5
4. Example: Filtering and Sorting a List
Use Case
- Filter products by price.
- Sort them alphabetically.
- Limit the number of displayed products.
<ul>
<li ng-repeat="product in products | filterByPrice:50 | orderBy:'name' | limitTo:3">
{{ product.name }} - ${{ product.price }}
</li>
</ul>
Processing Steps
filterByPrice:50
: Filters products with price ≥ 50.orderBy:'name'
: Sorts products alphabetically.limitTo:3
: Displays only the first 3 products.
5. Example: Chaining Filters for Search and Display Control
Use Case
- Convert input to lowercase.
- Filter search results.
- Limit the number of results.
<input type="text" ng-model="searchQuery" placeholder="Search products">
<ul>
<li ng-repeat="product in products | filter:searchQuery | limitTo:5">
{{ product.name | lowercase }}
</li>
</ul>
Processing Steps
filter:searchQuery
: Filters products based on user input.limitTo:5
: Displays up to 5 products.lowercase
: Converts product names to lowercase.
6. Performance Considerations
🔹 Minimize the number of filters inside ng-repeat
for large datasets.
🔹 Use track by
in ng-repeat
to avoid unnecessary DOM updates.
🔹 Precompute expensive calculations in the controller instead of relying on filters in the view.