Angular Filter

Posted on Updated on

 

 

 

 

What is Filter in AngularJS?

Filters are used for formatting data displayed to the user. They can be used in view templates, controllers or services. AngularJS comes with a collection of built-in filters as given below, but it is easy to define your own as well.

The general syntax in templates is as follows:

{{ expression [| filter_name[:parameter_value] ... ] }}

Build-in AngularJS filter

Name Description
filter Selects a subset of items from array and returns it as a new array.
currency Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default symbol for current locale is used.
number Formats a number as text.
date Formats date to a string based on the requested format.
json Allows you to convert a JavaScript object into JSON string.
lowercase Converts string to lowercase.
uppercase Converts string to uppercase.
limitTo Creates a new array or string containing only a specified number of elements. The elements are taken from either the beginning or the end of the source array, string or number, as specified by the value and sign (positive or negative) of limit. Other array-like objects are also supported (e.g. array subclasses, NodeLists, jqLite/jQuery collections etc). If a number is used as input, it is converted to a string.
orderBy Returns an array containing the items from the specified collection, ordered by a comparator function based on the values computed using the expression predicate.

Currency Filter Example :-

In HTML Template Binding
{{ currency_expression | currency : symbol : fractionSize}}
In JavaScript
$filter('currency')(amount, symbol, fractionSize)
Snippet example here:-



Currency : {{currencyValue}} Filter with Currency Symbol and Fraction : {{1234.1324 | currency : "USD$" :4}}

Currency : {{currencyValue}} Filter with Fraction : {{currencyValue | currency : 4}}
<hr/>		


Date filter example :

In HTML Template Binding
{{ date_expression | date : format : timezone}}
In JavaScript
$filter('date')(date, format, timezone)
Snippet example here:-


 Date : {{todayDate}} Filter with medium date format : {{dateInTimestamp | date:'medium'}}
 
 Date : {{todayDate}} Filter with full date format : {{dateInTimestamp | date: fullDate}}
 
 Date : {{todayDate}} Filter format date : {{dateInTimestamp | date:'yyyy-MM-dd HH:mm:ss Z'}}
 <hr/> 


Number filter example :

In HTML Template Binding
{{ number_expression | number : fractionSize}}
In JavaScript
$filter('number')(number, fractionSize)
Snippet example here:-
Number : {{numberValue}} Filter with Fraction 3 : {{numberValue | number:3}}

Json filter example :

In HTML Template Binding
{{ json_expression | json : spacing}}
In JavaScript
$filter('json')(object, spacing)
Snippet example here:-


 JSON : {{JSONValue}} Filter : {{JSONValue | json}}
 
 JSON : {{JSONValue}} Filter with spacing : {{JSONValue | json :10}}
 <hr/> 


Uppercase and Lowercase filter example :

In HTML Template Binding
{{ lowercase_expression | lowercase}}
{{ uppercase_expression | uppercase}}
In JavaScript
$filter('lowercase')()
$filter('uppercase')()
Snippet example here:-


 Name Value is {{name}}
 
 Upper Case : {{name | uppercase}}
 
 Lower Case : {{name | lowercase}}
 <hr/> 


 filter example :

In HTML Template Binding
{{ filter_expression | filter : expression : comparator : anyPropertyKey}}
In JavaScript
$filter('filter')(array, expression, comparator, anyPropertyKey)
Snippet example here:-
<p>
	<p>
		Search : <input type="text" ng-model="searchQuery"/> 
	</p>
	<table border="1">
		<tr>
			<th>ID</th>
			<th>Type</th>
		</tr>
		<tr ng-repeat="item in listOfItem | filter : searchQuery">
			<td>{{item.id}}</td>
			<td>{{item.type}}</td>
		</tr>
	</table>
	<hr/>	
</p>

How to Create custom filter?

Writing your own filter is very easy: just 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.

angular.module("myApp",[]).filter('reverse', function() {
 return function(input, uppercase) {
 input = input || '';
 var out = '';
 for (var i = 0; i < input.length; i++) {
 out = input.charAt(i) + out;
 }
 // conditional based on optional argument
 if (uppercase) {
 out = out.toUpperCase();
 }
 return out;
 };
})</pre>

HTML binding here



<pre>

<div>
 <input ng-model="greeting" type="text">
 No filter: {{greeting}}
 Reverse: {{greeting|reverse}}
 Reverse + uppercase: {{greeting|reverse:true}}
 Reverse, filtered in controller: {{filteredGreeting}}
</div>


Complete Example here :-

<html ng-app="myApp">
<head>
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</head>
<body ng-controller="filterController">
	<h1> Angular Build-in Filter Example </h1>
	<hr/>
	<p>
		Currency : {{currencyValue}} Filter with Currency Symbol and Fraction : {{currencyValue | currency : "USD$" :4}}
		<br/>
		Currency : {{currencyValue}} Filter with Fraction : {{currencyValue | currency : 4}}
		<hr/>	
	</p>	

<p>
	Date : {{todayDate}} Filter with medium date format : {{dateInTimestamp | date:'medium'}}
	<br/>
	Date : {{todayDate}} Filter with full date format : {{dateInTimestamp | date: fullDate}}
	<br/>
	Date : {{todayDate}} Filter format date : {{dateInTimestamp | date:'yyyy-MM-dd HH:mm:ss Z'}}
	<hr/>	
</p>

<p>
	Number : {{numberValue}} Filter with Fraction 3 : {{numberValue | number:3}}
	<hr/>	
</p>

<p>
	JSON : {{JSONValue}} Filter  : {{JSONValue | json}}
	<br/>
	JSON : {{JSONValue}} Filter with spacing : {{JSONValue | json :10}}
	<hr/>	
</p>

<p>
	Name Value is {{name}}
	<br/>
	Upper Case   : {{name | uppercase}}
	<br/>
	Lower Case   : {{name | lowercase}}
	<hr/>	
</p>

<p>
	<p>
		Search : <input type="text" ng-model="searchQuery"/> 
	</p>
	<table border="1">
		<tr>
			<th>ID</th>
			<th>Type</th>
		</tr>
		<tr ng-repeat="item in listOfItem | filter : searchQuery">
			<td>{{item.id}}</td>
			<td>{{item.type}}</td>
		</tr>
	</table>
	<hr/>	
</p>
<p>
<input ng-model="greeting" type="text"><br>
  No filter: {{greeting}}<br>
  Reverse: {{greeting|reverse}}<br>
  Reverse + uppercase: {{greeting|reverse:true}}<br>
  Reverse, filtered in controller: {{filteredGreeting}}<br>
</p>
</body>
<script type="text/javascript">
angular.module("myApp",[])
.controller("filterController",function($scope){
	$scope.todayDate = new Date();
	$scope.dateInTimestamp = $scope.todayDate.getTime();
	$scope.currencyValue = 1234.33;
	$scope.numberValue = 123.456789;
	$scope.JSONValue = "[{'key':'value'}]";
	$scope.name="Sample Angular Filter Example";
	$scope.listOfItem = [
			{ "id": "5001", "type": "None" },
			{ "id": "5002", "type": "Glazed" },
			{ "id": "5005", "type": "Sugar" },
			{ "id": "5007", "type": "Powdered Sugar" },
			{ "id": "5006", "type": "Chocolate with Sprinkles" },
			{ "id": "5003", "type": "Chocolate" },
			{ "id": "5004", "type": "Maple" }
		]
})
.filter('reverse', function() {
  return function(input, uppercase) {
    input = input || '';
    var out = '';
    for (var i = 0; i < input.length; i++) {
      out = input.charAt(i) + out;
    }
    // conditional based on optional argument
    if (uppercase) {
      out = out.toUpperCase();
    }
    return out;
  };
})
</script>

</html>




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s