Working with AngularJS Filters

angular-js

Working with AngularJS Filters

Filters in AngularJS provide a powerful way to format and transform data displayed to users. They can be applied directly in templates, allowing you to customize how data appears without modifying the data itself. In this tutorial, we’ll cover the most commonly used built-in filters, how to create custom filters, and best practices for using filters effectively in AngularJS applications.

Table of Contents

What are AngularJS Filters?

AngularJS filters are functions used to modify the appearance of data displayed in the view. Filters are typically added to expressions within templates and apply formatting or transformations to data, such as converting a number to a currency or filtering items in an array.

Filters are applied using the | (pipe) character, which acts as a separator between the data and the filter function.

Popular Built-In Filters

AngularJS provides several built-in filters that are commonly used to format or transform data:

currency Filter

Formats numbers as currency, adding the appropriate currency symbol. By default, it uses the dollar sign ($).

{{ amount | currency }}

date Filter

Formats date objects or strings into a specified date format. Common formats include 'shortDate', 'medium', and 'fullDate'.

{{ today | date:'fullDate' }}

uppercase and lowercase Filters

Converts text to uppercase or lowercase.

{{ name | uppercase }}

filter Filter

Filters an array based on a specified criteria.

{{ items | filter:searchText }}

orderBy Filter

Orders an array by the specified key in ascending or descending order.

{{ items | orderBy:'propertyName' }}

Using Multiple Filters

You can chain multiple filters together using the pipe character. For instance, to display a number as currency and uppercase the text:

{{ amount | currency | uppercase }}

This flexibility allows you to apply multiple transformations to data in a single expression, providing greater control over data presentation.

Creating Custom Filters

When built-in filters do not meet specific needs, you can create custom filters. Custom filters allow you to define unique transformations based on your application’s requirements.

Step 1: Define the Custom Filter

To create a custom filter, use the filter() method on your AngularJS module. The custom filter function should return a function that takes input and returns a transformed value.


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

This example defines a reverse filter that reverses a given string.

Step 2: Use the Custom Filter in HTML

Once defined, you can use your custom filter in the template just like a built-in filter:

{{ 'Hello' | reverse }}

This would display olleH on the page.

Best Practices for Using Filters

While filters can greatly enhance data presentation, here are some best practices to ensure efficient use of filters:

  • Minimize Filter Usage in Large Loops: Applying filters within large ng-repeat loops can affect performance, so use them cautiously in large datasets.
  • Create Reusable Custom Filters: If you frequently need specific data transformations, consider creating reusable custom filters instead of applying complex expressions multiple times.
  • Filter in Controller When Possible: For complex data transformations, consider handling the data in the controller or service layer rather than relying heavily on filters in the view.

Examples of Filters in Action

Let’s create a small application that demonstrates some of these filters in action, including custom filters.

Step 1: Project Setup

Create the following files in your project directory:


my-angular-app/
├── index.html
├── app.js
└── angular.min.js
    

Step 2: Define the Controller and Filters in app.js

In app.js, define a controller and custom filters:


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

app.controller("MainController", function($scope) {
    $scope.amount = 1234.56;
    $scope.date = new Date();
    $scope.name = "AngularJS Filters";
    $scope.items = [
        { name: "Apple", price: 2 },
        { name: "Banana", price: 1 },
        { name: "Cherry", price: 3 }
    ];
});

app.filter('reverse', function() {
    return function(input) {
        return input.split('').reverse().join('');
    };
});
    

Step 3: Use Filters in index.html

In index.html, apply various filters to data:

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title>AngularJS Filters Example</title>
    <script src="angular.min.js"></script>
    <script src="app.js"></script>
</head>
<body ng-controller="MainController">
    <h1>Working with AngularJS Filters</h1>

    <h3>Currency Filter</h3>
    <p>Amount: {{ amount | currency }}</p>

    <h3>Date Filter</h3>
    <p>Date: {{ date | date:'fullDate' }}</p>

    <h3>Uppercase Filter</h3>
    <p>Name in Uppercase: {{ name | uppercase }}</p>

    <h3>OrderBy Filter</h3>
    <ul>
        <li ng-repeat="item in items | orderBy:'price'">
            {{ item.name }} - ${{ item.price }}
        </li>
    </ul>

    <h3>Custom Reverse Filter</h3>
    <p>Reversed Name: {{ name | reverse }}</p>

</body>
</html>
    

This example demonstrates the usage of both built-in and custom filters in an AngularJS application.

Conclusion

Filters in AngularJS offer a flexible, efficient way to format and transform data in views. From simple formatting with built-in filters to complex transformations with custom filters, mastering filters can greatly enhance your AngularJS applications. Start exploring filters to improve the data presentation in your projects today!