AngularJS filters

Priyanka Patwal
Last Updated: May 13, 2022

Introduction

Everyone has probably heard the term filters. People nowadays prefer to share their images after applying various filters on any social networking site or portfolio. We all know why: to make it look good.

Filters in AngularJS, on the other hand, allow us to format data on any website for UI presentations without affecting the original format. In layman's terms, angularJS allows us to make a section of a website interactive and visually appealing.

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

The Basic Idea of Filters in AngularJS

Angular comes with a default formatter that allows us to format data and display it in your view or pass it as an input to another variable. AngularJS comes with a list of Filter components by default, which can be added to our data by including a pipe (|) with expression. 

Following is the general syntax for applying filters:

{{expression | filterName:parameter }}

List of AngularJS Filters

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

FilterDescription
NumberUses a comma and a fraction to format numeric data into text.
CurrencyFormats numeric data into the desired currency and fraction format.
DateFormats date to string in the specified format
UppercaseConverts string to uppercase
LowercaseConverts string to lowercase

Filter

 

Returns a new array after filtering an array based on supplied criteria.
orderBySorts an array according to a predicate expression.
JSONConverts JavaScript object into a JSON string
limitToReturns new array containing a specified number of elements from an existing array

 

Let’s see these filters one by one.

Number Filter

A number filter is used for formatting numeric data as text with comma and specified fraction size. The number filter displays an empty string if a specified expression does not produce a valid number.

Syntax: {{ number_expression | number:fractionSize}}

Example:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
</head>
<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:

Currency Filter

The currency filter formats a numeric value as a currency. When no currency symbol is provided, the default symbol for the current locale is used.

Syntax: {{ expression | currency : 'currency_symbol' : 'fraction'}}

Example:

<!DOCTYPE html>
<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
</head>
<body ng-app >
Enter Amount:<input type="number" ng-model= "price"><br>
The amount is: {{price | currency }}
</body>
</html>

 

Output:

Date filter

The date filter formats date to string based on the specified format.

Syntax: {{ date_expression | date : 'format'}}

Example:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
</head>
<body ng-app >
<h1>Date Filter of AngularJS </h1>
    <div ng-init="person.DOB = 323234234898">
        Default date: {{person.DOB| date}} <br />
        Short date: {{person.DOB| date:'short'}} <br />
        Long date: {{person.DOB | date:'longDate'}} <br />
        Year: {{person.DOB | date:'yyyy'}} <br />
    </div>
</body>
</html>

 

Output:

 

Uppercase/lowercase filter

The uppercase filter converts a string to uppercase, and the lowercase filter converts the string to lower case.

Syntax: 

{{expression | lowercase}} or {{expression | uppercase}}

 

Example: 

<!DOCTYPE html>
<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
</head>
<body ng-app >
<h1>Uppercase Filter of AngularJS </h1>
<div ng-init="firstName='coding'; lastName='ninjas'">
Upper case: {{firstName + ' ' +lastName | uppercase}} </div>
</body>
</html>

 

Output:

Filter

Filter selects elements from an array based on the specified criteria and 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.4.8/angular.min.js"></script> 
<body> 
<div ng-app="myApp" ng-controller="namesCtrl"> 
<ul> 
  <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> 
  <p>The names containing the letter "A".</p> 
  </body> 
</html>

 

Output:

In the example above, searchCriteria contains a text supplied in the input box that will be used to filter items from an array myArr using the filter:searchCriteria expression.

orderBy filter

The orderBy filter returns a sorted array based on a specified expression predicate.

Syntax: {{ expression | orderBy : predicate_expression : reverse}}

Example:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
</head>
<body ng-app="myApp" >
<h1>OrderBy Filter of AngularJS</h1>
    <div ng-controller="myController">
        <select ng-model="SortOrder">
            <option value="+name">Name (asc)</option>
            <option value="-name">Name (dec)</option>
        </select>
        <ul ng-repeat="person in persons | orderBy:SortOrder">
            <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';
        });
    </script>
</body>
</html>

 

Output: 

In Ascending order of Name

In Descending order of Name:

Apart from these Builtin filters, angularJS also provides the flexibility of making custom filters, let’s see how.

 

Custom Filters in AngularJS

The built-in filters cover a wide range of common use cases, such as formatting dates, currencies, and limiting the number of items displayed, among others. These filters are both helpful and provide insight into how we can improve our workflow when developing Angular apps.

But, angular JS provides a method for us to create our own customised filter. Writing your own filter is very easy. The steps are given below:

  1. Register a new filter factory function with your module. Internally, this uses the filterProvider. This factory function should return a new filter function which takes the input value as the first argument. Any filter arguments are passed in as additional arguments to the filter function.
  2. The filter function should be a pure function, which means that it should always return the same result given the same input arguments and should not affect 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.

Let’s understand with the help of an example.

Example:

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-filter-reverse-production</title>
  <script src="//code.angularjs.org/1.7.7/angular.min.js"> 
  </script>
  <script src="script.js"></script> 
</head>
<body ng-app="ReverseFilter">
<h1>Custom Filter of AngularJS</h1>
<div ng-controller="ReverseController">
<input ng-model="msg" type="text"><br>
  
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:

This was all about filters in angularJS, let’s move on to frequently asked questions on this topic.

Frequently Asked Questions

1.How do you combine filters with expressions?

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

 

2. What is the significance of a filter in AngularJS?

Ans: 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 pipe | sign. 

 

3. What type of filters can be applied in AngularJS?

Ans: There are various types of filters like number, currency, uppercase, orderBy, etc.

 

Key Takeaways

Filters format an expression's value for display to the user. They can be applied to view templates, controllers, and services. AngularJS includes a number of built-in filters, but it is also simple to create your own.

In this article, we’ve explained both for your convenience. Do give it a read.

Happy Learning!!

 

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think