This post describes AngularJS Filters with examples. Both AngularJS Custom and built-in filters are explained in great details with help of live examples. We will learn using common AngularJS built-in filters, using them in view templates
as well as in javaScript. We will also learn how to create a custom filter
for specific cases.
AngularJS Filters are mainly used to transform the data from the way it is stored to a human-readable format. Filters DO NOT MODIFY the data they applied upon, but provides on the fly conversion of that data into required format. Common usage of filters could be : show text in lower/upper case, display a timestamp in user specified format, add a currency symbol to a number etc.
AngularJS built-in Filters.
Following are the commonly used built-in filters.
Filter | Description |
---|---|
lowercase | lowercase filter |
uppercase | uppercase filter |
currency | currency filter |
number | number filter |
date | date filter |
json | json filter |
limitTo | limitTo filter |
orderBy | orderBy filter |
filter | filter filter |
Filters can be applied on View Templates and on data in Controllers/Service/Directives.
On view level, filters are applied on expressions separated with PIPE.
{{ expression | filter }}
Filters can be chained:
{{ expression | filter1 | filter2 | ... }}
Filters can accept arguments
{{ expression | filter:argument1:argument2:.. }}
Let’s see an example using AngularJS built-in filters.
<html> <head> <title>AngularJS Filter Example</title> </head> <body ng-app="myApp" class="ng-cloak"> <div ng-controller="AppController as ctrl"> <div> Name in UPPERCASES: {{ctrl.name | uppercase}} </div> <div> Name in lowercases: {{ctrl.name | lowercase}} </div> <div> First 3 letters of Name in lowercases: {{ctrl.name | lowercase | limitTo:3}} </div> <div> Quantity as a number: {{ctrl.quantity | number}} </div> <div> Quantity as a number with 3 decimals: {{ctrl.quantity | number:3}} </div> <div> Price with a currency: {{ctrl.price | currency}} </div> <div> Price with a Specific Currency : {{ctrl.price | currency:'EUR'}} </div> <div> JSON object: {{ctrl.jsonObj | json}} </div> <div> Date with default format (timestamp): {{ctrl.startAt}} </div> <div> Date with default 'date' format: {{ctrl.startAt | date}} </div> <div> Date with specific built-in format: {{ctrl.startAt | date:'short'}} </div> <div> Date with custom format: {{ctrl.startAt | date:"MM/dd/yyyy 'at' h:mma"}} </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"> </script> <script type="text/javascript"> angular.module('myApp', []) .controller('AppController', [function() { var self = this; self.name = "Shaun Pollock" self.price = 1000; self.quantity = 5; self.jsonObj = {strng: 'bla', num: 123}; self.startAt = new Date().getTime(); }]); </script> </body> </html>
Output:
Above example uses AngularJS built-in filters, namely lowercase, uppercase, date, number, currency, limitTo & json. What is important to understand that while applying filter like : {{ctrl.name | uppercase}} , The real value in ctrl.name does not change at all. Instead, data is dynamically formatted to uppercase on view only which is what user will see on screen.
To work with Arrays, AngularJS provides following filters: limitTo, orderBy & filter.
Let’s see them with help of examples.
a) limitTo Example
The limitTo filter takes either a string or an array of elements and returns a subset from the beginning or the end of the array (if the argument passed is -ve). Syntax is as follows:
{{ expression | limitTo : limit : begin}}
where limit is the number of elements. If limit is negative, selection will be done from the end of string/array. begin is the position/index to start with, it defaults to 0.
<html> <head> <title>AngularJS Filter Example</title> </head> <body ng-app="myApp" class="ng-cloak"> <div ng-controller="AppController as ctrl"> <div> Name : {{ctrl.name | limitTo:3}} </div> <div> Name : {{ctrl.name | limitTo:3:2}} </div> <div> Name : {{ctrl.name | limitTo:-2}} </div> <div> Items: {{ctrl.items | limitTo:5}} </div> <div> Items: {{ctrl.items | limitTo:5:2}} </div> <div> Items From Reverse: {{ctrl.items | limitTo:-2}} </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"> </script> <script type="text/javascript"> angular.module('myApp', []) .controller('AppController', [function() { var self = this; self.name = "Shaun Pollock" self.items = [10,20,30,40,50,60,70,80,90,100]; }]); </script> </body> </html>
Output:
b) orderBy Example
orderBy filter takes an array and order it by one ore more predicate expressions. Syntax is as follows:
{{ expression | orderBy : predicate_expression : reverse}}
Predicate_expression is used to order array elements. Option Boolean argument (reverse) can be used to sort the array in reverse order. The simplest form of a predicate expression is a string, which is the name of the field (the key of each object) to order the array by, with an optional + or – sign before the field name to decide whether to sort ascending or descending by the field. The predicate expression can also be passed a function, in which case the return value of the function will be used (with simple , = comparisons) to decide the order. Finally, the predicate expression can be an array, in which case each element of the array is either a string or a function. AngularJS will then sort it by the first element of the array, and keep cascading to the next element if it is equal.
<html> <head> <title>AngularJS Filter Example</title> </head> <body ng-app="myApp" class="ng-cloak"> <div ng-controller="AppController as ctrl"> <table class="players"> <tr> <th>Name</th> <th>Matches</th> <th>Averagee</th> </tr> <tr ng-repeat="player in ctrl.players | orderBy:'-avg'"> <td>{{player.name}}</td> <td>{{player.matches}}</td> <td>{{player.avg}}</td> </tr> </table> </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"> </script> <script type="text/javascript"> angular.module('myApp', []) .controller('AppController', [function() { var self = this; self.players= [{name:'Shaun Pollock', matches:'400', avg:60}, {name:'Lance Klusner', matches:'210', avg:87}, {name:'Alan Donald', matches:'450', avg:21}, {name:'Gary Kirsten', matches:'370', avg:66}, {name:'Harschel Gibbs', matches:'420', avg:77}]; }]); </script> </body> </html>
Output:
c) filter Example
‘filter’ filter selects a subset of items from array based on predicates or function, and returns it as a new array. Syntax is as follows:
{{ filter_expression | filter : expression : comparator}}
Expression can be string, object or function.
Comparator is used in determining if the expected value (from the filter expression) and actual value (from the object in the array) should be considered a match.It can be one of true/false/function(expected,actual).
<html> <head> <title>AngularJS Filter Example</title> </head> <body ng-app="myApp" class="ng-cloak"> <div ng-controller="AppController as ctrl"> <label> <input type="radio" ng-model="ctrl.filterOption" value="string">String</label> <input type="radio" ng-model="ctrl.filterOption" value="object">Object <input type="radio" ng-model="ctrl.filterOption" value="function">Function </label><br/> <div ng-if="ctrl.filterOption==='string'"> <label>Search: <input ng-model="ctrl.searchText"></label> <label>Exact Match <input type="checkbox" ng-model="ctrl.exactMatch"></label><br> <table id="searchTextResults"> <tr> <th>Name</th><th>Sport</th><th>Age</th><th>Retired</th> </tr> <tr ng-repeat="player in ctrl.players | filter:ctrl.searchText:ctrl.exactMatch"> <td>{{player.name}}</td> <td>{{player.sport}}</td> <td>{{player.age}}</td> <td>{{player.retired}}</td> </tr> </table> </div> <div ng-if="ctrl.filterOption==='object'"> <table id="searchTextResults"> <tr> <th>Name</th><th>Sport</th><th>Age</th><th>Retired</th> </tr> <tr ng-repeat="player in ctrl.players | filter:ctrl.obj"> <td>{{player.name}}</td> <td>{{player.sport}}</td> <td>{{player.age}}</td> <td>{{player.retired}}</td> </tr> </table> </div> <div ng-if="ctrl.filterOption==='function'"> <table id="searchTextResults"> <tr> <th>Name</th><th>Sport</th><th>Age</th><th>Retired</th> </tr> <tr ng-repeat="player in ctrl.players | filter:ctrl.fun"> <td>{{player.name}}</td> <td>{{player.sport}}</td> <td>{{player.age}}</td> <td>{{player.retired}}</td> </tr> </table> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"> </script> <script type="text/javascript"> angular.module('myApp', []) .controller('AppController', [function() { var self = this; self.players = [ {name: 'Shaun Pollock' , sport: 'cricket' , age: 45, retired: true}, {name: 'Roger Federer' , sport: 'tennis' , age: 34, retired: false}, {name: 'Usain Bolt' , sport: 'sprint' , age: 32, retired: false}, {name: 'Maria Sharapova', sport: 'tennis' , age: 29, retired: false}, {name: 'Jonty Rhodes' , sport: 'cricket' , age: 37, retired: true}, {name: 'Andre Agasi' , sport: 'tennis' , age: 42, retired: true}, {name: 'The Undertaker' , sport: 'wrestling' , age: 49, retired: false}, {name: 'Goldberg' , sport: 'wrestling' , age: 47, retired: true}, {name: 'Schumacker' , sport: 'formula1' , age: 45, retired: true}, {name: 'Justin Henin' , sport: 'tennis' , age: 41, retired: true} ]; self.filterOption='string'; self.searchText=''; self.exactMatch = false; self.obj={sport: 'tennis', retired:false}; self.fun = function(player) { return player.sport === 'tennis' && player.retired === true; } }]); </script> </body> </html>
Output:
Any filter (built-in or custom) can be injected into any service, controller or directive by adding the word “Filter” at the end of the name of the filter, and injecting it. For example, we can use currency filter in our controller as follows:
angular.module('myApp', []) .controller('AppController', ['currencyFilter', function(currencyFilter) { var self=this; self.amount=1000; var currencyInEur = currencyFilter(self.amount,'EUR'); }]);
First parameter to the filter function is the input to work upon. Rest of the arguments are same as in View Templates.
Let’s see few examples to understand them in detail.
a) orderBy filter example
Below is the same orderBy filter example [we developed earlier] with Controller this time.
<html> <head> <title>AngularJS Filter Example</title> </head> <body ng-app="myApp" class="ng-cloak"> <div ng-controller="AppController as ctrl"> <table class="players"> <tr> <th>Name</th> <th>Matches</th> <th>Averagee</th> </tr> <tr ng-repeat="player in ctrl.sortedPlayers"> <td>{{player.name}}</td> <td>{{player.matches}}</td> <td>{{player.avg}}</td> </tr> </table> </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"> </script> <script type="text/javascript"> angular.module('myApp', []) .controller('AppController', ['orderByFilter',function(orderByFilter) { var self = this; self.players= [{name:'Shaun Pollock', matches:'400', avg:60}, {name:'Lance Klusner', matches:'210', avg:87}, {name:'Alan Donald', matches:'450', avg:21}, {name:'Gary Kirsten', matches:'370', avg:66}, {name:'Harschel Gibbs', matches:'420', avg:77}]; self.sortedPlayers = orderByFilter(self.players, '-avg'); }]); </script> </body> </html>
Output:
b) ‘filter’ filter example
<html> <head> <title>AngularJS Filter Example</title> </head> <body ng-app="myApp" class="ng-cloak"> <div ng-controller="AppController as ctrl"> <h4>Filter With String</h4> <div> <table> <tr> <th>Name</th><th>Sport</th><th>Age</th><th>Retired</th> </tr> <tr ng-repeat="player in ctrl.filterdPlayersWithString"> <td>{{player.name}}</td> <td>{{player.sport}}</td> <td>{{player.age}}</td> <td>{{player.retired}}</td> </tr> </table> </div> <h4>Filter With Object</h4> <div> <table> <tr> <th>Name</th><th>Sport</th><th>Age</th><th>Retired</th> </tr> <tr ng-repeat="player in ctrl.filterdPlayersWithObject"> <td>{{player.name}}</td> <td>{{player.sport}}</td> <td>{{player.age}}</td> <td>{{player.retired}}</td> </tr> </table> </div> <h4>Filter With Function</h4> <div> <table> <tr> <th>Name</th><th>Sport</th><th>Age</th><th>Retired</th> </tr> <tr ng-repeat="player in ctrl.filterdPlayersWithFunction"> <td>{{player.name}}</td> <td>{{player.sport}}</td> <td>{{player.age}}</td> <td>{{player.retired}}</td> </tr> </table> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"> </script> <script type="text/javascript"> angular.module('myApp', []) .controller('AppController', ['filterFilter', function(filterFilter) { var self = this; self.players = [ {name: 'Shaun Pollock' , sport: 'cricket' , age: 45, retired: true}, {name: 'Roger Federer' , sport: 'tennis' , age: 34, retired: false}, {name: 'Usain Bolt' , sport: 'sprint' , age: 32, retired: false}, {name: 'Maria Sharapova', sport: 'tennis' , age: 29, retired: false}, {name: 'Jonty Rhodes' , sport: 'cricket' , age: 37, retired: true}, {name: 'Andre Agasi' , sport: 'tennis' , age: 42, retired: true}, {name: 'The Undertaker' , sport: 'wrestling' , age: 49, retired: false}, {name: 'Goldberg' , sport: 'wrestling' , age: 47, retired: true}, {name: 'Schumacker' , sport: 'formula1' , age: 45, retired: true}, {name: 'Justin Henin' , sport: 'tennis' , age: 41, retired: true} ]; self.searchText='cri'; self.exactMatch = false; self.obj={sport: 'tennis', retired:false}; self.fun = function(player) { return player.sport === 'tennis' && player.retired === true; } self.filterdPlayersWithString = filterFilter(self.players,self.searchText,self.exactMatch); self.filterdPlayersWithObject = filterFilter(self.players,self.obj); self.filterdPlayersWithFunction = filterFilter(self.players,self.fun); }]); </script> </body> </html>
Output:
Built-in filters are great but not enough. In those specific situations where you want to implement your own filter, you can create custom filters.
General syntax for writing custom filter is shown below:
app.filter('mycustomfilter', [function () { return function (item) { //do something with item return something; }; }]);
Module’s filter function is used to create custom filters.It follows the same syntax as Controllers or services. First parameter is the name of filter which we can use in HTML. Second parameter is an array, where in you can specify any dependencies your filter might wants to be injected in (same as for controllers e.g.). Take special note of the return statement : it returns a function which gets invoked each time angularJS calls the filter.
Then in HTML you can use this filter like
Do something special with new filter: {{ctrl.somevar | mycustomfilter}}
You can additionally pass arguments
app.filter('mycustomfilter', [function () { return function (item, arg1, arg2, arg3) { //do something with item return something; }; }]);
Do something special with new filter: {{ctrl.somevar | mycustomfilter:arg1:arg2:arg2}}
Let’s write a custom filter which (like built-in uppercase filter) shows an input string in UPPERCASES.
<html> <head> <title>AngularJS Filter Example</title> </head> <body ng-app="myApp" class="ng-cloak"> <div ng-controller="AppController as ctrl"> <h4>Custom Filter Example</h4> Initial value : {{ctrl.samplestr}} <br/> Filtered Value in UpperCases : {{ctrl.samplestr | convertToUppercase}} </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"> </script> <script type="text/javascript"> angular.module('myApp', []) .controller('AppController', [function() { var self = this; self.samplestr = "webSystique"; }] ).filter('convertToUppercase', [function () { return function (str) { return str.toUpperCase(); }; }]); </script> </body> </html>
Output:
If you like tutorials on this site, why not take a step further and connect me on Facebook , Google Plus & Twitter as well? I would love to hear your thoughts on these articles, it will help improve further our learning process.
In this post we will be developing a full-blown CRUD application using Spring Boot, AngularJS, Spring Data, JPA/Hibernate and MySQL,…
Spring Boot complements Spring REST support by providing default dependencies/converters out of the box. Writing RESTful services in Spring Boot…
Being able to start the application as standalone jar is great, but sometimes it might not be possible to run…
Spring framework has taken the software development industry by storm. Dependency Injection, rock solid MVC framework, Transaction management, messaging support,…
Let's secure our Spring REST API using OAuth2 this time, a simple guide showing what is required to secure a…
This post shows how an AngularJS application can consume a REST API which is secured with Basic authentication using Spring…