Creating Custom Filters in AngularJS

Loading

AngularJS provides several built-in filters like uppercase, orderBy, currency, etc. However, sometimes you need custom filters to meet specific requirements. AngularJS allows you to create your own filters to transform data dynamically.

Filters can format, transform, or manipulate data before display
Can be applied to expressions in HTML templates
Reusable across the application


1. Defining a Custom Filter

A custom filter in AngularJS is created using the .filter() method in a module.

Basic Syntax

app.filter('filterName', function() {
return function(input, arg1, arg2) {
// Modify input as needed
return modifiedInput;
};
});

Where:

  • input → The original data passed to the filter
  • arg1, arg2 → Optional parameters
  • Returns → Transformed data

2. Example: Reverse a String

Let’s create a filter that reverses a string.

Implementation

var app = angular.module('myApp', []);

app.filter('reverse', function() {
return function(input) {
if (!input) return ''; // Handle empty input
return input.split('').reverse().join('');
};
});

Using the Filter in HTML

<p>Original: {{ 'AngularJS' }}</p>
<p>Reversed: {{ 'AngularJS' | reverse }}</p>

Output:

Original: AngularJS  
Reversed: SJralugnA

3. Example: Capitalize First Letter of Each Word

A filter that capitalizes each word in a sentence.

Implementation

app.filter('capitalize', function() {
return function(input) {
if (!input) return '';
return input.replace(/\b\w/g, function(letter) {
return letter.toUpperCase();
});
};
});

Using the Filter in HTML

<p>{{ 'hello world' | capitalize }}</p>

Output:

Hello World  

4. Example: Filter Array by Keyword

A filter to search a list of items dynamically.

Implementation

app.filter('searchFilter', function() {
return function(items, searchText) {
if (!searchText) return items;
searchText = searchText.toLowerCase();
return items.filter(function(item) {
return item.toLowerCase().includes(searchText);
});
};
});

Using the Filter in HTML

<input type="text" ng-model="searchText" placeholder="Search...">
<ul>
<li ng-repeat="name in names | searchFilter:searchText">
{{ name }}
</li>
</ul>
app.controller('FilterController', function($scope) {
$scope.names = ["Alice", "Bob", "Charlie", "David", "Eve"];
});

Feature:

  • Dynamically filters the list based on user input.

5. Example: Convert Bytes to KB, MB, or GB

A filter to convert file sizes dynamically.

Implementation

app.filter('fileSize', function() {
return function(size) {
if (size < 1024) return size + ' B';
else if (size < 1048576) return (size / 1024).toFixed(2) + ' KB';
else if (size < 1073741824) return (size / 1048576).toFixed(2) + ' MB';
else return (size / 1073741824).toFixed(2) + ' GB';
};
});

Using the Filter in HTML

<p>File Size: {{ 1048576 | fileSize }}</p>

Output:

File Size: 1.00 MB  

6. Example: Mask Sensitive Data (Phone Number)

A filter to mask phone numbers for privacy.

Implementation

app.filter('maskPhone', function() {
return function(number) {
if (!number || number.length !== 10) return number;
return '****-***-' + number.slice(-3);
};
});

Using the Filter in HTML

<p>Phone: {{ '9876543210' | maskPhone }}</p>

Output:

Phone: ****-***-210  

7. Example: Display “Yes” or “No” for Boolean Values

A filter that converts true or false to "Yes" or "No".

Implementation

app.filter('yesNo', function() {
return function(value) {
return value ? 'Yes' : 'No';
};
});

Using the Filter in HTML

<p>Subscribed: {{ true | yesNo }}</p>
<p>Premium User: {{ false | yesNo }}</p>

Output:

Subscribed: Yes  
Premium User: No

8. Using Filters in Controllers

You can apply custom filters inside controllers.

Example: Using a Filter in a Controller

app.controller('TestController', function($scope, $filter) {
var text = "hello world";
$scope.result = $filter('capitalize')(text);
});

Displaying the Filtered Data

<p>{{ result }}</p>

Output:

Hello World  

Leave a Reply

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