Click here to Skip to main content
15,881,600 members
Articles / Web Development / HTML

Angular Tutorial - Part 4: Understanding and Implementing Filters

Rate me:
Please Sign up or sign in to vote.
4.81/5 (35 votes)
7 Jul 2015CPOL7 min read 32.1K   963   20   2
Basic concepts of filters in Angular

Introduction

In this article, we will look at the concept of filters in Angular. We will look at a few built in filters and see how we can create custom filters in Angular.js.

Link to complete series:

  1. Angular Tutorial - Part 1: Introduction to Angular.js
  2. Angular Tutorial - Part 2: Understanding Modules and Controllers
  3. Angular Tutorial - Part 3: Understanding and Using Directives
  4. Angular Tutorial - Part 4: Understanding and Implementing Filters
  5. Angular Tutorial - Part 5: Understanding and Implementing Services
  6. Angular Tutorial - Part 6: Building and Validating Data Entry Forms
  7. Angular Tutorial - Part 7: Understanding Single Page Applications and Angular Routing

Background

There are times when we would want to post process the retrieved data before showing it on the view. One example of this could be that we might want to format a particular string value in a certain format, for example, we might have retrieved the price of a product from the database and we want to display in the local currency format. Or perhaps, we might want to apply some conversion rate on the retrieved value and display the local value price of the product. Another example of such could be that we might want to have the contents of the application translated to the local language before displaying it to the user. Or in the simplest of scenarios, we want to sort the retrieved data in some particular order before displaying it to the user.

Filters in Angular provide an excellent way of post processing the retrieved data, do some data manipulation before rendering it on the view. Filters provide a clear syntax to perform data manipulation and formatting as per our needs without writing too much code. There are a lot of built in filters available in Angular and Angular also lets us create our own custom filters.

In this article, we will look at how we can use filters in Angular, we will look at the usage of some built in filters and try to create a custom filter to understand how we can create our own filters to cater to our application needs.

Using the Code

Let's start by looking at how we can use filters in our application. Using filters is pretty straight forward. We just need to pipe (|) the data that we want to process into the filter.

JavaScript
{{ myData | filter }}

If we want to provide some additional formatting information as a parameter to the filters, we can do that by using : with the filter expression as:

JavaScript
{{ myData | filter:'parameter' }}

If we want to apply multiple filters on any data, then we can chain these filter expressions one after the other using the same pipe (|) symbol.

JavaScript
{{ myData | filter | yetAnotherFilter }}

Now to fully get the grasp how filters work, let us look at the few built in filters in Angular.

uppercase and lowercase

Perhaps the most simple case of post processing the data is to change the casing of a given string. Angular provides two filters called uppercase and lowercase for this purpose. We just need to pipe the data into this filter and the string will be converted accordingly. Following image shows how this can be done in the view.

Image 1

number

The number filter lets the application know that the given string should be treated as a number. It can be used in the following manner:

JavaScript
{{ 10 | number }}

If we want to specify the number of decimal places, we can pass that as a parameter to the filter. So let's say that we want to look at the five decimal places, the filter usage will look like:

JavaScript
{{ quantity | number:5 }}

The following image shows how we can use the number filter in the view where quantity is the variable defined on scope.

Image 2

date

Date filter lets us treat any given string as data and also lets us control the display format of the date.

JavaScript
{{ today | date }}

If we want to take control of the display format, we can use the format string as an argument to the filter.

JavaScript
{{ today | date:'dd, MMMM, yyyy' }}

Note: To look at the various date format specifiers for date, please refer to Angular documentation.

currency

Currency filter also works same as date and number. If we want to indicate that a particular string should be treated as currency, we can use this filter.

JavaScript
{{ price | currency }}

Also, if we want to provide our own currency symbol, then we can pass that too as a parameter to the filter.

JavaScript
{{ price | currency:'Rs ' }}

limitTo

limitTo is a filter that can let us limit the number of items we want to render on the view. If we use limitTo on a string, it will limit the number of characters that will be displayed on the view.

JavaScript
{{ message | limitTo:5}}

If we use limitTo filter in a ng-repeat expression, it will limit the number of items that will be shown to the user from that collection. So if we want to show only two items from a list, we can use the limitTo attribute in the following manner:

Image 3

limitTo with ngRepeat is particularly very useful when we want to implement paging functionality on the views.

orderBy

orderBy filter can be used to sort the data based on some specific criteria. Let's say we want to display the books displayed in the order of IDs, we can specify it in form of a filter as:

JavaScript
ng-repeat="book in books | orderBy: ID"

If we want to order it in the descending order of IDs, we can use the - to indicate that we want to order in the descending order as:

JavaScript
ng-repeat="book in books | orderBy: -ID"

filter

filter is another filter available in Angular which can be used to filter some items from a collection. It will look at all the fields of the collection and will display the items that contain the string present in the filter parameter. So if we want to show the books that contain the word 'test', we do this in the following manner:

JavaScript
ng-repeat="book in books | filter:'test'"

Note: In the sample application, the use of filters like orderBy, filter are generalized and provided as user selectable values. The following image shows the screenshot of how it looks. Please look at the sample application to see how this is being done by using the above mentioned filters in action.

Image 4

json

The json filter can be used to view the json representation of any object. This is very useful when we have to call any remote service that is expecting a json payload. This could also be used for debugging and troubleshooting purposes. So let's say if we want to view the json payload of books collection, we can do something like the following:

JavaScript
{{ books | json }}

And when we look at the result on the view, we can see the json payload for this collection of books:

Image 5

Using Filters in Controllers and Services

The filter usage that we have seen so far is from the views perspective. But there could be scenarios where we might want to use the filters from the JavaScript components like controllers and services. Angular also lets us use the filters in the components where we can use the $filter to call the filter in the following manner:

JavaScript
$scope.allCapsMessage = $filter("uppercase")($scope.message);

If we want to pass the filter parameter, we can pass it as the second argument. For example, if we want to filter a number to have up to 5 places of decimal, we can do that in the following manner:

JavaScript
$scope.conversionRate = $filter("number")(62.3, 5);

Creating a Custom Filter

Angular also lets us create our own custom filters for the scenarios where the built in filters are not sufficient. Let's see how we can create a custom filter in Angular. Let's say we want to create a filter where we want to create a filter that will calculate the power of the given number with the provided parameter. If no parameter is provided, then the power value will be taken as 1.

To create the custom filter, we need to register the filter definition with the Angular module in the following manner:

JavaScript
angular.module('myAngularApplication').filter('power', function () {
    
    return function (input, powerValue) {

        // Check if power value is falsy
        if (!powerValue) {
            powerValue = 1;
        }

        // Use Math.pow to find the power and return it
        return Math.pow(input, powerValue);
    }
});

What the above code is doing is that it is creating a filter called power that will take an input and a parameter for the power value and uses Math.Pow to return the result.

From the usage perspective, now this filter can be used as any other filter. So {{ 2 | power }} will return 2 and {{ 2 | power:4 }} will return 16.

Points of Interest

In this article, we looked at the basic of filters in Angular. We have looked at a few built in filters in Angular. We saw how powerful filters can be when it comes to some post processing and data manipulations. We saw various ways of using filters and how we can write our own custom filters. This article has been written from a beginners' perspective. I hope this has been informative.

History

  • 7th July, 2015: First version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India

I Started my Programming career with C++. Later got a chance to develop Windows Form applications using C#. Currently using C#, ASP.NET & ASP.NET MVC to create Information Systems, e-commerce/e-governance Portals and Data driven websites.

My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems. IMO, C# is the best programming language and I love working with C# and other Microsoft Technologies.

  • Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4

If you like my articles, please visit my website for more: www.rahulrajatsingh.com[^]

  • Microsoft MVP 2015

Comments and Discussions

 
GeneralMy vote of 5 Pin
D V L17-Mar-16 8:22
professionalD V L17-Mar-16 8:22 
QuestionA simple needed modification Pin
julie_iskander24-Aug-15 4:07
julie_iskander24-Aug-15 4:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.