Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
The Basic Idea of Filters in AngularJS
3.
List of AngularJS Filters
3.1.
Number Filter
3.2.
Currency Filter
3.3.
Date Filter
3.4.
Uppercase/lowercase filter
3.5.
Filter
3.6.
OrderBy filter
4.
Custom Filters in AngularJS
5.
Frequently Asked Questions
5.1.
What are filters in AngularJS?
5.2.
What type of filters can be applied in AngularJS?
5.3.
What is the significance of a filter in AngularJS?
5.4.
How to filter data from a list in AngularJS?
5.5.
How do you combine filters with expressions?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

AngularJS filters

Introduction

Everyone has probably heard the term filters. Filters in AngularJS allow us to format data on any website. We use them only for UI presentations, which do not affect the original format. In layman's terms, AngularJS allows us to make a section of a website interactive and visually appealing.

Angularjs Filters

In this article, we’ll learn about various filters in AngularJS. So, without any further ado, let’s get started!

The Basic Idea of Filters in AngularJS

AngularJS comes with a default format that allows us to format data and display it in our view or pass it as input to another variable. In AngularJS, filters are used to format the value of an expression for a display to the user. They can be used in templates, controllers, or services to transform data. AngularJS provides several built-in filters, such as currency, date, uppercase filters, etc. It also allows for the creation of custom filters. Filters are applied to expressions using the "pipe" character (|), followed by the filter name and any necessary arguments.

Following is the general syntax for applying filters:

{{ expression | filter }}
You can also try this code with Online Javascript Compiler
Run Code

 

We can also pass arguments to a filter by using a colon (:) followed by the argument value. 

{{expression | filterName:parameter }}
You can also try this code with Online Javascript Compiler
Run Code

 

There is another way of adding filters in AngularJS. We can add filters to directives. We can add filters to directives using the “pipe” character(|), followed by the filter name.

<div my-directive>{{ expression | filterName }}</div>

List of AngularJS Filters

The following table shows the commonly used filters in AngularJS along with their description.

Filter Name Description
Number Formats a number as text.
Currency Formats a number as a currency.
Date Formats a date using a specified format.
Uppercase Converts a string to uppercase.
Lowercase Converts a string to lowercase.
Filter Selects a subset of items from an array.
OrderBy Orders an array by an expression.
JSON Formats an object as a JSON string.
LimitTo Limits an array or string to a specified number of elements or characters.

 

We can also create your own custom filters by using the filter function in AngularJS.

Custom filters are useful when you want to perform specific formatting or calculations on an expression that is not provided by the built-in filters.

Number Filter

We use the "number" filter to format a number as text with commas and specified fraction size. We will get an empty string displayed if a specified expression does not produce a valid number. The number filter can be used in a template using the following syntax:

{{ number_expression | number : fractionSize}}
You can also try this code with Online Javascript Compiler
Run Code

 

  • number_expression: The number we want to format.
  • fractionSize: (optional) The number of decimal places to include in the formatted number. If not specified, it defaults to the value defined in the $locale service or 2 if the $locale service is not defined.

 

Example:

<!DOCTYPE html>
<html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<!--
    In this, we see the use of the number filter. The first output is the number filter on 100000, and the second one is the output for the entered price, in this case, which is 124.80. The third one is for precision up to 3 decimal places. The fourth one is using the number filter along with the directive “ng-bind”.
-->

    <body ng-app >
        <h1>Number Filter of AngularJS</h1>
        Enter Price: <input type="number" ng-model="Price" /> <br />
        100000 | number = {{100000 | number}} <br />
        Price | number = {{Price | number}} <br />
        Price | number:3 = {{Price | number:3}} <br />
        Price | number = <span ng-bind="Price | number"></span>
    </body>
</html>

 

Output:

Number filter

Currency Filter

The currency filter can be used to format a number as a currency value.  When no currency symbol is provided, the default symbol for the current $locale is used.

The filter can be applied to a variable within an AngularJS template using the following syntax:

{{ variable | currency : symbol : fractionSize}}

 

In the above syntax, the variable is the numeric value to be formatted, the symbol is the currency symbol to be used (e.g., "$" for US dollars). And fractionSize is the number of decimal places to be displayed. 

Example:

<!DOCTYPE html>
<html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<!--
    In this, we see the use of the currency filter changing the number to currency.
-->

    <body ng-app >
        <h1>Currency Filter of AngularJS </h1>
        Let amount be:100.256 <br>
        The amount is: {{100.256 | currency }}
    </body>
</html>

 

Output:

Currency filter

As we can see from the above output, when no symbol is defined for currency, the filter takes the dollar ‘$’ as default.

Date Filter

In AngularJS, we use the date filter to format a date. We can use the date filter in a template or a controller. We can also use predefined formats like 'shortDate', 'mediumDate', 'longDate', 'fullDate'.

Syntax: 

{{ date_expression | date : 'format'}}
You can also try this code with Online Javascript Compiler
Run Code

 

In the above syntax, the date_expression is the date we want to format. The format string is the formatting style we want, like 'MM/DD/YYYY' or DD/MM/YYYY.

Example:

<!DOCTYPE html>
<html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<!--
    In this, we see the use of the date filter along with different formats.
-->

    <body ng-app >
        <h1>Date Filter of AngularJS </h1>
        <div ng-init="person.DOB = 111111111111">
            Default date: {{person.DOB| date}} 
            <br />
            Short date: {{person.DOB| date:'short'}}
            <br />
            Medium date: {{person.DOB| date:'medium'}} 
            <br />
            Long date: {{person.DOB | date:'longDate'}} 
            <br />
            Custom Format 1: {{person.DOB | date: 'dd/MM/yyyy'}} 
            <br/>
            Custom Format 2: {{person.DOB | date: 'MM/dd/yyyy'}} 
            <br/>
            Custom Format 3: {{person.DOB | date: 'yyyy-MM-dd'}} 
            <br/>
            Year: {{person.DOB | date:'yyyy'}} <br />
        </div>
    </body>
</html>

 

Output:

Date filter

Uppercase/lowercase filter

In AngularJS, we use a filter to convert a string to uppercase or lowercase. This filter is called "uppercase" or "lowercase," respectively, and is used in the template like so:

{{ someVariable | uppercase }}

or

{{ someVariable | lowercase }}

 

We can also use this filter in our controller. Another way is by injecting the $filter service and calling the uppercase or lowercase filter on a string like so:

$filter('uppercase')(someVariable);

or

$filter('lowercase')(someVariable);

 

Example: 

<!DOCTYPE html>
<html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    <!--
        In this, we see the use of the uppercase and the lowercase filter.
        -->
    <body ng-app="myApp" >
        <h1>Uppercase & Lowercase Filter of AngularJS </h1>
        <div ng-init="firstName='coding'; lastName='ninjas'">
            Upper case: {{firstName + ' ' +lastName | uppercase}} 
        </div>
        <div ng-controller="myCtrl">
            Lower case: {{lowerCaseText}}
        </div>
        <script>
            var app = angular.module('myApp', []);
            app.controller('myCtrl', function($scope, $filter) {
            $scope.originalText = "Coding Ninjas";
            $scope.lowerCaseText = $filter('lowercase')($scope.originalText);
            });
            
        </script>
    </body>
</html>

 

Output:

Uppercase and lowercase

Filter

Filter selects a subset of items from an array based on some specified criteria. It returns the selected items in a new array.

Syntax: 

{{ expression | filter : filter_criteria }}

 

Example:

<!DOCTYPE html>
<html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<!--
    In this, we are using of the filter to filter out the names containing the character A in them, out of all the names provided.
-->

    <body>
        <div ng-app="myApp" ng-controller="namesCtrl">
            <ul>
                <h1> Filter filter of AngularJS</h1>
                {{names}}
                <p>The names amoung the above array containing the letter "A", are: </p>
                <li ng-repeat="x in names | filter : 'A'"> 
                    {{ x }} 
                </li>
            </ul>
        </div>
        <script> 
            angular.module('myApp', []).controller('namesCtrl', function($scope) { 
              $scope.names = ['Osheen','Mahima','Vindyavi','Amit','Aditya','Tripti']; 
            }); 
              
        </script> 
    </body>
</html>

 

Output:

Filter

OrderBy filter

The orderBy filter returns a sorted array based on a specified expression predicate. One important note to remember is that the orderBy filter returns a new array. It doesn't sort the original array.

Syntax: 

{{ expression | orderBy : predicate_expression : reverse}}

 

Example:

<!DOCTYPE html>
<html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<!--
    In this, we see the use of the orderBy filter for arranging elements into ascending and descending orders.
-->

    <body ng-app="myApp" >
        <h1>OrderBy Filter of AngularJS</h1>
        <div ng-controller="myController">
            <h3> Decending Order</h3>
            <ul ng-repeat="person in persons | orderBy:SortOrder">
                <li>{{person.name}} - {{person.phone}}</li>
            </ul>
            <h3> Ascending Order</h3>
            <ul ng-repeat="person in persons | orderBy:SortOrder1">
                <li>{{person.name}} - {{person.phone}}</li>
            </ul>
        </div>
        <script>
            var myApp = angular.module('myApp', []);
            
            myApp.controller("myController", function ($scope) {
            
                $scope.persons = [{ name: 'John', phone: '512-455-1276' },
                            { name: 'Vaishnavi', phone: '899-333-3345' },
                            { name: 'Priyanka', phone: '511-444-4321' },
                            { name: 'Toohina', phone: '145-788-5678' },
                            { name: 'Akshita', phone: '433-444-8765' },
                            { name: 'Pakhi', phone: '218-345-5678' }]
                
                $scope.SortOrder = '-name';
                $scope.SortOrder1 = '+name';
            });
        </script>
    </body>
</html>

 

Output: 

Order by filter

Custom Filters in AngularJS

There are several built-in filters in AngularJS. They cover many common use cases, such as formatting dates and currencies, limiting the number of items displayed, etc. These filters are helpful and provide insight into how we can improve our workflow when developing Angular apps.

But, AngularJS allows us to create our customized filter. Writing your filter is very easy. The steps are given below:

  • Register a new filter factory function with your module. Internally, this uses the filterProvider. This factory function should return a new filter function that takes the input value as the first argument. Any filter arguments are passed in as additional arguments to the filter function.
     
  • The filter function should be a pure function. It should always return the same result given the same input arguments and should not affect the external state.
     
  • For example, other AngularJS services. AngularJS relies on this contract and will, by default, execute a filter only when the inputs to the function change. Stateful filters are possible but less performant.

 

We can make any custom filter of our choice using the correct logic. It can be as simple as just capitalizing the first character to as complex as we want. Some of the custom filters can be:

  • Reverse
  • Currency of some particular country
  • Filter by date
  • Truncation, etc.

We can also make custom filters by combining two or more predefined or even custom-made filters. 

  • Reverse with uppercase
  • Currency with a round to two places
  • Filter by date range

Let’s understand with the help of some examples.

Example 1:

<!DOCTYPE html>
<html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    
    <!--
        In this, we are making customs filters one is for reversing and other is for uppercase. So n the second operation we are combining reverse with uppercase.
        -->
        
    <body ng-app="ReverseFilter">
        <h1>Custom Filter of AngularJS</h1>
        <div ng-controller="ReverseController">
            Content with No filter: {{msg}}<br>
            Content after Reverse filter: {{msg|reverse}}<br>
            Content after Reverse Filter in uppercase: {{msg|reverse:true}}<br>
        </div>
    </body>
    <script>
        (function(angular) {
          'use strict';
        angular.module('ReverseFilter', []).filter('reverse', function() {
          return function(input, uppercase) {
          input = input || '';
          var out = '';
          for (var x = 0; x < input.length; x++) {
          out = input.charAt(x) + out;
          }
          // conditional based on optional argument
          if (uppercase) {
            out = out.toUpperCase();
            }
            return out;
          };
        })
            .controller('ReverseController', ['$scope', 'reverseFilter', function($scope, reverseFilter) {
          $scope.msg = 'Coding Ninjas';
          $scope.filteredMessage = reverseFilter($scope.msg);
        }]);
        })(window.angular);
        
    </script>
</html>

 

Output:

Output Custom Filters1

 

Example 2:

<!DOCTYPE html>
<html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    
    <!--
        In this, we are making customs filters one is for converting a number to Indian currency and the second is for truncating longtext and the last one is for capitalizing only the first character.
        -->
        
    <body>
        <div ng-app="myApp" ng-controller="myCtrl">
            <h1>Custom Filters</h1>
            <h3>Filter for Indian Currency </h3>
            <p>Without filter: 1000 <br>
                Indian Currency: {{ 1000 | currency }}
            </p>
            <h3>Filter to truncate longtext </h3>
            <p>Without filter: Learn to Code <br>
                Truncated to 5 charachters: {{ "Learn to Code" | truncate:5 }}
            </p>
            <h3>Filter to capitalize only the first character </h3>
            <p>Without filter: learn to Code <br>
                After filter: {{ "learn to Code" | capitalize }}
            </p>
        </div>
    </body>
    <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function($scope) {});
        app.filter('currency', function() {
          return function(input) {
            return '₹' + input;
          };
        });
        app.filter('truncate', function() {
          return function(input, length) {
            if (input.length > length) {
              return input.substring(0, length) + '...';
            }
            return input;
          };
        });
        app.filter('capitalize', function() {
          return function(input) {
            return input.charAt(0).toUpperCase() + input.slice(1);
          };
        });
    </script>
</html>

 

Output: 

Output Custom filter 2

Frequently Asked Questions

What are filters in AngularJS?

Filters in AngularJS allow us to format data on any website. They can be used in templates, controllers, or services to transform data. 

What type of filters can be applied in AngularJS?

Various types of filters can be applied in AngularJS, like the number, currency, uppercase, orderBy, etc.

What is the significance of a filter in AngularJS?

AngularJS Filters allow us to format the data to display on UI without changing the original format. Filters can also be used with an expression or directives using the pipe | sign. 

How to filter data from a list in AngularJS?

In AngularJS, we can use the ‘filter’ filter to filter data from a list. It takes an array and a filter function as arguments and returns a new array containing only the items from the original array that pass the filter function's test.

How do you combine filters with expressions?

Filters can be applied to the result of another filter. This is called "chaining" and uses the following syntax: {{ expression | filter1 | filter2 | ... }}.

Conclusion

In this article, we learned about filters in AngularJS. We learned about the frequently used filters. We also learned that AngularJS provides many built-in filters, such as currency, date, uppercase filters, etc. It also allows for the creation of custom filters. 

Check out our articles if you think this blog has helped you enhance your knowledge and want to learn more. Visit our website to read more such blogs. 

  1. Introduction to AngularJS  
  2. React vs. Angular  
  3. Angular js vs. Nodejs 
  4. Difference between Angular and AngularJs 
  5. AngularJs Library 

For placement preparations, you must look at the problemsinterview experiences, and interview bundles. Enrol in our courses and refer to the mock tests and problems available; look at the Problem Sheets interview experiences, and interview bundle for placement preparations. You can also book an interview session with us.  

Consider our paid courses, however, to give your career a competitive advantage!

Happy Coding!

Live masterclass