How filters work internally in AngularJS?

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:

  1. Templates (Views){{ data | filterName }}
  2. 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) converts 1000 into a currency format.

2. How Filters Work Internally in AngularJS

Internally, AngularJS handles filters using the $filterProvider service, which is responsible for:

  1. Registering filters
  2. Retrieving filters
  3. 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.
  • $filterProvider stores it in an internal registry.

Step 2: Fetching a Filter

When a filter is used ($filter('filterName')), AngularJS internally:

  1. Looks up the filter in $filterProvider’s registry.
  2. Retrieves the filter function.
  3. 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:

  1. Parses the expression and detects the | (pipe operator).
  2. Identifies the filter (e.g., currency).
  3. Fetches the filter function from $filterProvider.
  4. Executes the function with the provided data.
  5. Replaces the original expression with the formatted output.

3. Built-in Filters in AngularJS

AngularJS provides several built-in filters:

Filter NameUsage ExampleDescription
currency`{{ 1000currency }}`
date`{{ todaydate:’yyyy-MM-dd’ }}`
filter`{{ itemsfilter:’searchText’ }}`
json`{{ objjson }}`
limitTo`{{ itemslimitTo:5 }}`
lowercase`{{ ‘HELLO’lowercase }}`
uppercase`{{ ‘hello’uppercase }}`
number`{{ 1234.56number:2 }}`
orderBy`{{ studentsorderBy:’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:

  1. Looks up filterName in $filterProvider.
  2. Retrieves the filter function.
  3. Passes input to the function.
  4. Returns the processed output.

Example: Retrieving a Filter Manually

var reverseFilter = $filter('reverse');
console.log(reverseFilter('hello')); // Output: "olleh"

Leave a Reply

Your email address will not be published. Required fields are marked *