In AngularJS, filters are used to format data displayed to users without modifying the original data model. They help transform and refine data in templates or controllers dynamically.
1. Understanding Filters in AngularJS
Filters in AngularJS work by taking input data, processing it, and returning a transformed output. They can be used in:
- Templates (Views) –
{{ data | filterName }} - Controllers & Services –
$filter('filterName')(data, args)
Example: Using a Filter in a Template
<p>{{ amount | currency }}</p>
- If
amount = 1000, this will display “$1,000.00” (default currency format).
Example: Using a Filter in a Controller
app.controller('MainCtrl', function($scope, $filter) {
var amount = 1000;
$scope.formattedAmount = $filter('currency')(amount);
});
$filter('currency')(amount)converts1000into a currency format.
2. How Filters Work Internally in AngularJS
Internally, AngularJS handles filters using the $filterProvider service, which is responsible for:
- Registering filters
- Retrieving filters
- Applying filters on expressions
Step-by-Step Internal Workflow
Step 1: Defining a Filter
Filters in AngularJS are registered using $filterProvider or app.filter().
Example:
app.filter('reverse', function() {
return function(input) {
return input.split('').reverse().join('');
};
});
🔍 How it works internally:
app.filter()registers the filter with$filterProvider.$filterProviderstores it in an internal registry.
Step 2: Fetching a Filter
When a filter is used ($filter('filterName')), AngularJS internally:
- Looks up the filter in
$filterProvider’s registry. - Retrieves the filter function.
- Executes the function with the provided input and arguments.
Step 3: Applying a Filter
When a filter is used in an AngularJS expression ({{ data | filterName }}), AngularJS:
- Parses the expression and detects the
|(pipe operator). - Identifies the filter (e.g.,
currency). - Fetches the filter function from
$filterProvider. - Executes the function with the provided data.
- Replaces the original expression with the formatted output.
3. Built-in Filters in AngularJS
AngularJS provides several built-in filters:
| Filter Name | Usage Example | Description |
|---|---|---|
currency | `{{ 1000 | currency }}` |
date | `{{ today | date:’yyyy-MM-dd’ }}` |
filter | `{{ items | filter:’searchText’ }}` |
json | `{{ obj | json }}` |
limitTo | `{{ items | limitTo:5 }}` |
lowercase | `{{ ‘HELLO’ | lowercase }}` |
uppercase | `{{ ‘hello’ | uppercase }}` |
number | `{{ 1234.56 | number:2 }}` |
orderBy | `{{ students | orderBy:’name’ }}` |
4. Custom Filters in AngularJS
Custom filters are created using app.filter(), which registers the filter with $filterProvider.
Example 1: Custom “Reverse” Filter
app.filter('reverse', function() {
return function(input) {
if (!input) return '';
return input.split('').reverse().join('');
};
});
Usage in HTML:
<p>{{ 'hello' | reverse }}</p>
Output: "olleh"
Example 2: Filtering an Array
app.filter('startsWithA', function() {
return function(items) {
return items.filter(item => item[0].toLowerCase() === 'a');
};
});
Usage in Controller:
$scope.names = ['Alice', 'Bob', 'Andrew', 'Charlie'];
Usage in HTML:
<ul>
<li ng-repeat="name in names | startsWithA">{{ name }}</li>
</ul>
Output: "Alice", "Andrew"
5. Performance Considerations
Filters can impact performance if used inefficiently, especially with large datasets.
Avoid Filters in Large Lists
<li ng-repeat="item in items | filter:searchText">{{ item }}</li>
Problem: Every digest cycle, AngularJS re-applies the filter, slowing down rendering.
Solution: Use ng-model-options or $watch
Instead of using filters in ng-repeat, pre-filter data in the controller:
$scope.filteredItems = $filter('filter')($scope.items, 'searchText');
🔹 Improvement: Reduces unnecessary re-filtering on every digest cycle.
6. $filterProvider – The Internal Mechanism
The $filterProvider internally stores and retrieves filters.
Here’s how it works:
Registering a Filter
Internally, when app.filter('filterName', function() { return function(input) {...} }) is called:
$filterProvider.register('filterName', function() {
return function(input) {
return modifiedInput;
};
});
- The function is registered inside AngularJS’s filter registry.
- It becomes available globally in templates and controllers.
Retrieving and Executing a Filter
When $filter('filterName')(input), AngularJS:
- Looks up
filterNamein$filterProvider. - Retrieves the filter function.
- Passes
inputto the function. - Returns the processed output.
Example: Retrieving a Filter Manually
var reverseFilter = $filter('reverse');
console.log(reverseFilter('hello')); // Output: "olleh"
