Angularjs

AngularJS Filters


Filters are used to format input data.These are most commonly used on arrays and tables with the ng-repeat directive. Pipe (|) character is used with filters.Chained filters are also possible to apply where filters are separated by pipe(|) character.We can pass additional arguments with the filters to format the result.

Angular JS has some inbuilt filters as below:

  • filter
  • currency
  • number
  • lowercase
  • uppercase
  • limitTo
  • orderBy
  • date
  • JSON
Filter

AngularJS filter component is applied in an array and used to get the subset of it.It can be applied on HTML template as well as in Javascript code.

Syntax

  • HTML Template:
{{filter expression|filter:expression:comparator}}
  •  Javascript Code:
$(filter)(array,expression,comparator);

Example:

<!DOCTYPE html>
<html>
<head>
<title>Angular Js Filters example</title>
</head>
<body ng-init="orders=[{name:'Samsung',quantity:'12'},
{name:'Nokia',quantity:'3'},
{name:'LG',quantity:'5'},
{name:'Apple',quantity:'8'}]">
<input type="text" ng-model="searchOrder"/></br></br>
<table>
<thead>List of orders</thead>
<tbody>
<tr>
<th>Item Name</th>
<th>No.of items Sold</th>
</tr>
<tr ng-repeat="order in Orders | filter:searchOrder>
<td>order.name</td>
<td>order.quantity</td> 
<tr>
</tbody>
</table>
</body>
</html>

Try It!

Currency

This is used to format currency again this is also applied to HTML template as well as in Javascript code.

Syntax

  • HTML Template
{{ currencyExpression | currency:symbol:fractionsize}}
  •  Javascript Code
$filter('currency')(number,symbol,fractionsize)

HTML Template Example:

<p>{{ 245 | currency:'₹'}}</p
<!--output: ₹245.00-->

<p>{{ 245 | currency}}</p>
<!--output: $245.00  //Default locale(symbol)-->

<p>{{ 245 | currency:'₹':4}}</p>
<!--output: ₹245.0000 //since fraction size is 4-->

Javascript Example:

<!--JS code-->
$scope.price = $filter('currency')(245,₹);
<!--HTML code-->
<p>{{price}}</p>
<!--output-->
 ₹245.00

<!--JS code-->
$scope.price = $filter('currency')(245);
<!--HTML code-->
<p>{{price}}</p>
<!--output-->
 $245.00

<!--JS code-->
$scope.price = $filter('currency')(245.45,₹,4);
<!--HTML code-->
<p>{{price}}</p>
<!--output-->
 ₹245.4500
Number

Used to format the number as text.It can be used with HTML or Javascript.

  • HTML Template Syntax:
{{numberExpression|number:fractionsize}}

Example:

<p>{{ 245.00 | number}}</p
<!--output: 245.00-->

<p>{{ 245.56| number:0}}</p>
<!--output: 245 -->

<p>{{ 245.56 | number:1}}</p>
<!--output: 245.6 (Here fraction size rounds off)-->
  •  Javascript Code Syntax:
$filter('number')(number,fractionsize);

Example:

<!--JS code-->
$scope.number= $filter('number')(245.00);
<!--HTML code-->
<p>{{number}}</p>
<!--output-->
 245.00

$scope.number= $filter('number')(245.47,0);
<!--HTML code-->
<p>{{number}}</p>
<!--output-->
 245

$scope.number= $filter('number')(245.47,1);
<!--HTML code-->
<p>{{number}}</p>
<!--output-->
 245.6
Lowercase/Uppercase

Used to convert the expressions to lowercase or uppercase.

Syntax

  • HTML Template:
<!-- lowercase syntax -->
{{expression| lowercase}}

<!-- uppercase syntax -->
{{expression| uppercase}}
  • Javascript Code:
<!-- lowercase expression-->
$filter('lowercase')(expression)

<!--uppercase expression-->
$filter('uppercase')(expression)

Example

{{ CodeGeeksLab | lowercase}}
<!-- prints codegeekslab-->

{{ CodeGeeksLab | uppercase}}
<!-- prints CODEGEEKSLAB-->
LimitTo

Used to select the subset or range of items from an array.It can be used to select items either from the beginning or from the end based on limit value positive or negative.

Syntax

  • HTML Template
{{ array_expression | limitTo : limit : begin}}

  •  Javascript Code
$filter('limitTo')(input,limit,begin);

Example:

<div ng-init="items=[10,20,40,50,60]">
</div>
<p> {{ items | limitTo:4}}
<!-- prints 10,20,40,50 -->
<p> {{items | limitTo:4:1}}</p>
<!-- prints  4 elements starting from index 1 i.e, 20,40,50,60-->

If limitTo is undefined original array will be printed.

Example:

index.html

<body ng-app="myApp" ng-controller="myController" ng-init = "orders= [{name:'Samsung',quantity:'12'},
{name:'Nokia',quantity:'3'},
{name:'LG',quantity:'5'},
{name:'Apple',quantity:'8'}]">
<table border=1>
<thead>Order details</thead>
<tbody>
<tr>
<th>Item Name</th>
<th>No.of items Sold</th>
</tr>
<tr ng-repeat="order in orders | limitTo:2">
<td>{{order.name}}</td>
<td>{{order.quantity}}</td> 
</tr>
</tbody>
</table>
</body>

app.js

angular.module('myApp',[]).controller('myController',function($scope){
});

Try It!

OrderBy

Used for sorting elements.Strings will be sorted alphabetically and numbers will be sorted numerically.

Syntax

  • HTML Template
{{ array_expression | orderBy :expression : reverse}}
  •  Javascript Code
$filter('orderBy')(inputexpression , expression ,reverse);

Here reverse is used to mention descending order.Usually “-” is used for it.

Example:

<div ng-init="students=[{name:"Jhon",age:'13'},
{name :  "Milan",age : '14'},
{name : "Andrew",age : '13'}]">
</div>
<div ng-repeat="stud in students | orderBy : '-age'">
<p>stud.name</p>
<p>stud.age</p>
</div>
Date

Used to format the date object.

Syntax

{{ date_object | date:format:timezone}}

Here default date format is “MMM d,y”(Jan 5, 2016).Timezone is optional.We have many date formats as below:

mediumyyyy(Four digit representation of year)hh(Hour in a day 01-12)
shortDateyy(Two digit representation of year)mm(Minute in an hour)
fullDateMMMM(Month like January)ss(Second in a minute)
longDateMM(Month in year like 01-12)HH(Hour in a day 00-24)
mediumDateEEEE(Day in week like Sunday-Monday)
shortTimeEEE(Day in week like Sun-Mon)
mediumTime
JSON

Used to filter the JSON string and prettifies it with indentation.It does not allow any extra parameters but simply formats with provided object to JSON string.

Syntax

{{ JSON_object | json}}

Example

<div ng-init="products={"Samsung":"s8","Nokia":"W10","Apple":"i7"}">
<p> {{ products | json}} </p>
</div>
<!-- Output
    {
      "Samsung" : "S8",
      "Nokia" : "W10",
      "Apple" : "i7"
   }
Custom Filters:

We can also define our own filters and can be used on expressions using ‘|’. Let’s create a simple filter

app.js

var app=angular.module('myApp',[]).controller('myController',function($scope){
});

app.filter('myFilter',function(){
   return function(input){ 
     console.log(input);	 
     return input.toUpperCase();	 
   }
});

index.html

<body ng-app="myApp" ng-controller="myController" ng-init = "orders= ['Samsung','Apple','Nokia']">
<table border=1>
<thead>Order details</thead>
<tbody>
<tr>
<th>Item Name</th>
</tr>
<tr ng-repeat="order in orders " >
<td>{{order| myFilter}}</td>
</tr>
</tbody>
</table>
</body>

Try It!

Here we have created a simple filter named myFilter and registered it with the application module.This converts the given expression to uppercase and returns it.We applied this filter in the view to convert each array item to uppercase.

Leave a Reply

Your email address will not be published. Required fields are marked *