AngularJS Filters - AngularJS Documentation for filter | W3schools

Filters are used to format the value of an expression for display to the user. They can be added to templates, controllers, directives or services and you can also define your own filters. Using filters, Angular lets you organize data so that it only displays data if it meets certain criteria.

Also Read: Angularjs Directives

AngularJS provides filters to transform data:

  • currency Format a number to a currency format.
  • date Format a date to a specified format.
  • filter Select a subset of items from an 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.

Let us now understand each filter with its syntax and an example.

Currency Filter:

The currency filter formats a number as currency. By default, the locale currency format is used.
Syntax:

{{ number | currency : symbol : fractionsize }}

Let us have a look at an example.

<!DOCTYPE html>

<html ng-app>

 <head>

<title> Angular Filter – Currency</title>

<script src=”http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js”></script>

</head>

 <body>

  <div ng-controller=”currencyController”>

  Quantity: <input type=”number” ng-model=”quantity”>

      Price: <input type=”number” ng-model=”price”>

      <p> Toal Default = {{ (quantity * price) | currency }}</p>

      <p>Total in INR = {{ (quantity * price) | currency :”INR ” }}</p>

 </div>

 <script src=”currencyController.js”></script>

</body>

</html>

 

The following Controller is used in this example. We set the initial state of the scope by attaching the properties quantity and price with values 1 and 10 respectively.

CurrencyControl.js

function currencyController($scope) {

    $scope.quantity = 1;

    $scope.price = 10;

}

 

You will see the following output in your browser. The default currency format is in USD($).

Output:

Q uantity: : Price:

Toal Default = {{ (quantity * price) | currency }}

Total in INR = {{ (quantity * price) | currency :”INR ” }}
Date Filter:

The date filter formats a date to a specified format.

The date can be a date object, milliseconds, or a datetime string like “2016-01-05T09:05:05.035Z”

By default, the format is “MMM d, y” (Jan 5, 2016).

Syntax:

{{ date | date : format : timezone }}

Let us have a look at an example.

<html>

<head>

    <title> Angular Filter – Date</title>

</head>

<body>

    <script type=”text/javascript” src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js”></script>

    <script type=”text/javascript”>

        var app = angular.module(‘MyApp’, [])

        app.controller(‘MyController’, function ($scope, $filter) {

            var date = new Date();

            $scope.ddMMyyyy = $filter(‘date’)(new Date(), ‘dd/MM/yyyy’);

            $scope.ddMMMMyyyy = $filter(‘date’)(new Date(), ‘dd, MMMM yyyy’);

           $scope.HHmmss = $filter(‘date’)(new Date(), ‘HH:mm:ss’);

            $scope.hhmmsstt = $filter(‘date’)(new Date(), ‘hh:mm:ss a’);

        });

    </script>

    <div ng-app=”MyApp” ng-controller=”MyController”>

        <u>dd/MM/yyyy format:</u><span ng-bind = “ddMMyyyy”></span><br>

        <u>dd, MMMM yyyy format:</u><span ng-bind = “ddMMMMyyyy”></span><br>

        <u>24 Hour time:</u><span ng-bind = “HHmmss”></span><br>

        <u>12 Hour time:</u><br /><span ng-bind = “hhmmsstt”></span><br>

    </div>

</body>

</html>

[post_middile_section_ad]

Output:

dd/MM/yyy format:23/12/2017

dd, MMMM yyyy format:23,December 2017

24 Hour time format:22:48:36

12 Hour time:10:48 PM

Filter & OrderBy Filter:

The filter filter allows us to filter an array, and return an array containing only the matching items.

This filter can only be used for arrays.

Syntax:

{{ arrayexpression | filter : expression : comparator }}

The orderBy filter allows us to sort an array.

By default, strings are sorted alphabetically, and numbers are sorted numerically.

Syntax

{{ array | orderBy : expression : reverse }}

 

Let us have a look at an example.

<!DOCTYPE html>

<html ng-app=””>

 <head>

<title> Angular Filter – FilterOrderBy</title>

<script src=”http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js”></script>

</head>

 <body>

 <div ng-controller=”playerController”>

 Name:<input type=’text’ ng-model=’filterName’/>

<ul>

  <li ng-repeat=”player in players |filter:filterName | orderBy:’name'”>

    {{ player.name + ‘ : ‘ + player.country }}

  </li>

</ul>

</div>

 <script src=”playerController.js”></script>

 </body>

</html>

We use the following controller in the above example.

playerController.js

function playerController($scope) {

        $scope.players = [ {name:’Elano Blumer’,country:’Brazil’},

            {name:’David James’,country:’England’},

            {name:’Iain Hume’,country:’Canada’}

                       ];

    }

 

You will see the following output in your browser. You can type in the input field to filter the list.

Output:

Name:

  • {{ player.name + ‘: ‘ + player.country }}

 

Json Filter:

The json filter converts a JavaScript object into a JSON string.

This filter can be useful when debugging your applications.

The JavaScript object can be any kind of JavaScript object.

Syntax:

{{ object | json : spacing }}

Let us have a look at an example.

<!DOCTYPE html>

<html>

<head>

<title>

AngularJs Filter – JSON </title>

<script src=”http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js”></script>

</head>

<body ng-app=””>

<div>

Default JSON Format

<pre>{{ {‘name’: ‘Suresh Dasari’,’age’: ’29’} | json }}</pre>

JSON Format with Spacing

<pre>{{ {‘name’: ‘Suresh Dasari’,’age’: ’29’} | json:10 }}</pre>

</div>

</body>

</html>

 

[post_middile_section_ad]

Output:

If you observe above code we declared two conditions with json filter one is without spaces and another one is with spaces. Now we will run and see the output of example.

Following is the result of json filter example in angularjs application.

Default JSON Format

{

“name”: “Suresh Dasari”,

“age”: “29”

}

JSON Format with Spacing

{

“name”: “Suresh Dasari”,

“age”: “29”

}

LimitTo Filter:

The limitTo filter returns an array or a string containing only a specified number of elements.

When the limitTo filter is used for arrays, it returns an array containing only the specified number of items.

When the limitTo filter is used for strings, it returns a string containing, only the specified number of characters.

When the limitTo filter is used for numbers, it returns a string containing only the specified number of digits.

Use negative numbers to return elements starting from the end of the element, instead of the beginning.

Syntax:

{{ object | limitTo : limit : begin }}

Let us have a look at an example.

<!DOCTYPE html>

<html  ng-app>

<head>

<title>Angular Filter – limitTo</title>

<script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.js”></script>

</head>

<body>

<div ng-controller=”limitController”>

Defined Array of Numbers: {{numbers}}<br>

<br>Limit  to:

<input type=”integer” ng-model=”limit”>

<p>Array after limiting to {{limit}} numbers : {{ numbers | limitTo:limit }}</p>

<p>{{xss}}</p>

</div>

</body>

<script src=”limitController.js”></script>

</html>

 

We us the following controller in our example.

limitController.js

function limitController($scope) {

$scope.numbers = [10,20,30,40,50,60,70,80,90,100];

$scope.limit = 5;

}

Output:

D efined Array of Numbers: [10,20,30,40,50,60,70,80,90,100]

Limit to:

Array after limiting to 5 numbers : [10,20,30,40,50]

Lowercase & Uppercase Filter:

The lowercase filter converts a string to lowercase letters.

Syntax:

{{ string | lowercase }}

The uppercase filter converts a string to uppercase letters.

Syntax:

{{ string | uppercase}}

Let us understand it with an example.

<!DOCTYPE html>

<html>

<head>

<title>Angular Filter – Uppercase and Lowercase</title>

<script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js”></script>

</head>

<body>

<div ng-app=”” ng-controller=”BlogController”>

Name: <input type=”text” ng-model=”name”><br>

Blog Name: <input type=”text” ng-model=”blogName”><br>

<br>

Name: {{name | uppercase}}

<br>

Blog Name : {{blogName | lowercase}}

</div>

<script src=”blogController.js”></script>

</body>

</html>

 

The following Controller is used in this example. We set the initial state of the scope by attaching the properties with upper and lowercase letters.

blogController.js

function BlogController($scope) {

$scope.name = “abc”,

$scope.blogName = “XYZ”

}

 

Output:

Name : abc

Blog Name : XYZ

[post_middile_section_ad]

Number Filter:

The number filter formats a number to a string.

Syntax:

{{ string | number : fractionsize}}
Let us understand it with an example.

<!DOCTYPE html>

<html>

<head>

<title>AngularJs Filter – Number</title>

<script src=”http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js”></script>

<script>

var app = angular.module(“AngularnumberApp”, []);

app.controller(“numberctrl”, function ($scope) {

$scope.sampleval = 52343.1435784;

});

</script>

</head>

<body ng-app=”AngularnumberApp”>

<div ng-controller=”numberctrl”>

Enter Number: <input type=”text” ng-model=”sampleval” /><br /><br />

Default Number expression:{{sampleval | number}}<br /><br />

Number with Decimal Value: {{sampleval | number:4}} <br /><br />

Number with Zero Decimals:{{sampleval | number:0}}

</div>

</body>

</html>

 

Following is the result of number filter example in angularjs.

Output:

Enter Number: 52343.1435784

Default Number expression:52,343.144

Number with Decimal Value: 52,343.1436

Number with Zero Decimals:52,343