AngularJS - Filters

By xngo on August 21, 2019

In AngularJS, filters are used to format data. They take the result of an expression, format it and then display the end result to the users. They follow the following syntax:

{{ expression | filter }}

Filters result can be applied to another filters and use the following syntax:

{{ expression | filter1 | filter2 | ... | filterN }}

Filters can have arguments and are written as follow:

{{ expression | filter:argument1:argument2:...:argumentN }}

AngularJS comes with a collection of built-in filters. They are:

  • currency: Format a number to a currency format.
  • date: Format a date to a specified format.
  • filter: Selects a subset of items from array and returns it as a new array.
  • json: Format an object to a JSON string.
  • limitTo: Limits an array/string, into a specified number of elements/characters.
  • lowercase: Format a string to lower case.
  • number: Format a number to a string.
  • orderBy: Orders an array by an expression.
  • uppercase: Format a string to upper case.

Apply filter to expression

The example below will format the name to upper case.

<div ng-app="" ng-init="name='Kevin'">
    <p>The name in upper case is {{ name | uppercase }}.</p>
</div>

Output

The name in upper case is KEVIN.

Apply filter to directive

The example below will sort the list of persons by name in descending order. By default, it is sorted in ascending but I set the reverse order to true.

<div ng-app="" ng-init="persons=[
                                    {name:'Joe', age: 11},
                                    {name:'Anne', age: 22},
                                    {name:'Peter', age: 33}
                                ]">
    <ol>
        <li ng-repeat="x in persons | orderBy:'name':true">
            {{ x.name + ' is ' + x.age + ' years old.' }}</li>
    </ol>
</div>

Output

1. Peter is 33 years old.
2. Joe is 11 years old.
3. Anne is 22 years old.

Apply filter to an array based on user input

By setting the ng-model directive on an input field, we can use the value of the input field as an expression in a filter.

<div ng-app="" ng-init="names=['John', 'Anne', 'Peter']">
    <input type="text" ng-model="searchTerm"/>
    <ol>
        <li ng-repeat="x in names | filter: searchTerm">
            {{ x }}</li>
    </ol>
</div>

This will result in a dynamic search field where the list grows and shrinks according to the terms matched. Try it out by typing in the following input field.

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.