In a previous guide on AngularJS, we got a look at the basic implementation of AngularJS. In this article we will look at Filter Components, which are integral parts to angular.
This article covers the following areas of AngularJS with implementation and examples:
Angular provides filter components for filtering, organizing, and arranging the values based on input requirements.
A filter returns a subset of a new array based on the conditions and expressions from the array. Filters can be used in HTML Template as well as in JavaScript.
Syntax
1{{ filter_expression | filter : expression : comparator}}
1$filter("filter")(array, expression, comparator);
In the HTML Template, we use filter
in the pipe expression |
as shown above. This pipe function takes the result from first expression and sends the output to second expression.
Explanation with Example (filter in HTML Template):
1<!-- ng-app - attech an application module to the page -->
2<html ng-app="myApp">
3
4<!-- ng-controller - attech a controller functions to the page -->
5<body ng-controller="myCtrl">
6<!-- ng-init to initialize products as an array -->
7<div ng-init="products = [{ name : 'sony', price : 23, quantity : 4},
8 { name : 'nokia', price : 45.3, quantity : 3},
9 { name : 'samsung', price : 65, quantity : 6},
10 { name : 'motorola', price : 12.7, quantity : 8},
11 { name : 'micromax', price : 39.75, quantity : 3},
12 { name : 'lenovo', price : 10, quantity : 2}]">
13</div>
14
15<!-- input filed to type expression to be filter -->
16<div>
17 <label>Search</label>
18 <input ng-model="searchText" class="form-control" />
19</div>
20
21<table class="table">
22 <tbody>
23 <tr>
24 <th>Name</th>
25 <th>Price</th>
26 <th>Quantity</th>
27 </tr>
28 <!-- filter based on value of searchText -->
29 <tr ng-repeat="p in products | filter:searchText">
30 <td>{{p.name}}</td>
31 <td>{{p.price}}</td>
32 <td>{{p.quantity}}</td>
33 </tr>
34 </tbody>
35</table>
36
37</body>
38<html>
In the example, products
is an actual array that shows a set of filtered values based on the input, "searchText"
.
Plunker for filter in HTML Template.
1// register myCtrl to the angular module app.
2app.controller("myCtrl", function($scope, $filter) {
3 // create an array as $scope.products
4 $scope.products = [
5 { name: "sony", price: 23, quantity: 4 },
6 { name: "nokia", price: 45.3, quantity: 3 },
7 { name: "samsung", price: 65, quantity: 6 },
8 { name: "motorola", price: 12.7, quantity: 8 },
9 { name: "micromax", price: 39.75, quantity: 3 },
10 { name: "lenovo", price: 10, quantity: 2 }
11 ];
12
13 // create a mirror copy of actual array
14 $scope.mirrorProducts = angular.copy($scope.products);
15
16 // bind function to ng-keyup event.
17 $scope.filterFunc = function() {
18 // override the value of mirrorProduct with filtered value
19 $scope.mirrorProducts = $filter("filter")($scope.products, {
20 $: $scope.searchText
21 });
22 };
23});
1<body ng-controller="myCtrl">
2 <div class="form-group col-lg-10">
3 <label class="label label-default" style="margin-left:10px">Search</label>
4 <input ng-model="searchText" class="form-control" ng-keyup="filterFunc()" />
5 </div>
6
7 <table class="table">
8 <tbody>
9 <tr>
10 <th>Name</th>
11 <th>Price</th>
12 <th>Quantity</th>
13 </tr>
14 <!-- use mirrorProducts array to display changes because we are overriding the mirrorProducts array with the original products array every time -->
15 <tr ng-repeat="p in mirrorProducts">
16 <td>{{p.name}}</td>
17 <td>{{p.price}}</td>
18 <td>{{p.quantity}}</td>
19 </tr>
20 </tbody>
21 </table>
22</body>
When we use filtering in Angular's controller, we have to load the dependency in the controller's function as $filter
. So, we are using $filter('filter')(array, expression, comparator)
.
The type of filter component is filter
, hence the code $filter('filter_component')
i.e $filter('filter')
.
In the above example, I use the $scope.mirrorProducts
variable and override each time the user presses any key in input field. Since we are showing only filtered information to the user, we have to create a subset of the actual array and override it each time to display correct results on page.
What if I don't create a mirror copy of actual array ?
If I do not create a mirror copy of the actual array, then, at the time of filtering, the actual array gets overridden and we are left with just the filtered version. Thus, we lose our original array values.
We use $
as the expression while filtering an array.
$
is a special property that can be used to apply filter on any property of the object.Plunker for filter in JavaScript
Angular provides a better way to format a price and display it on the page. The currency filter formats a number as currency, setting the number to the proper decimal value (like $25.70). This filter can be used in the HTML Template as well as in JavaScript.
In HTML Template
1{{ currency_expression | currency : symbol : fractionSize}}
Here, currency expression is the numerical value that will be formatted by a currency filter to display numerical value as a price with a specified currency symbol.
The second parameter after the pipe expression is a name of filter component i.e currency
. symbol
and fractionSize
are the option values. symbol
is for your local currency to format the number to price and fractionSize
determines the number of digits after the decimal point to which the price will be recorded.
For example :
1<p>{{25 | currency }}</p>
2<!-- This will print result as $25.00. Note that the default fractionSize is 2. -->
3
4<p>{{25 | currency : "₹" }}</p>
5<!--This will print result as ₹25.00. -->
6
7<p>{{25.46 | currency : "₹" : 4}}</p>
8<!--This will print result as ₹25.4600 because fractionSize is 4 decimal places. -->
In JavaScript Template
1$filter("currency")(amount, symbol, fractionSize);
symbol
and fractionSize
are the same in JS as in HTMP Template. Amount
is the numerical value which has to be converted into currency format. $filter
is an instance of the filter component service which is injected into the controller's function as a dependency.
For example :
Currency Format:
1<!--JS code-->
2$scope.price = $filter('currency')(25);
3
4<!--html code-->
5<p>{{price}}</p>
6
7<!--output-->
8$25.00
Currency Format with Custom Symbol:
1<!--JS code-->
2$scope.price = $filter('currency')(25,'₹');
3
4<!--html code-->
5<p>{{price}}</p>
6
7<!--Output-->
8₹25.00
Currency Format with Custom Decimal Points:
1<!--JS code-->
2$scope.price = $filter('currency')(25,'₹',4);
3
4<!---Html Code-->
5<p>{{price}}</p>
6
7<!--Output-->
8₹25.0000
see Plunker for more examples.
The number filter formats a number as text. This filter can be used in the HTML Template as well as in JavaScript.
HTML Template
1{{ number_expression | number : fractionSize}}
number_expression
is the number which has to be formatted into text. number
is the value to be formatted. fractionSize
is the decimal point to display after formatting and rounding-up as well if number_expression
has more decimal values.
For Example :
1<p>{{24.76 | number}}</p>
2<!--this will print result as 24.76-->
3
4<p>{{24.76 | number : 0}}</p>
5<!--this will print the result as 24-->
6
7<p>{{24.76 | number : 1}}</p>
8<!--this will print result as 24.8-->
JavaScript Code
1$filter("number")(number, fractionSize);
$filter
instance of filter components. $flter(number)
type of filter components. number
will be the format. fractionSize
is the count of the decimal point display after formatting.
For Example :
1$scope.number = $filter("number")(25.76);
2// this will print a result as 25.76
3
4$scope.number = $filter("number")((25.76: 0));
5//this will print a result as 25
6
7$scope.number = $filter("number")((25.76: 1));
8//this will print a result as 25.8
see Plunker for more.
The date filter provides a better way to represent the date in string format (MMM d, y h:mm:ss a
will show as Sep 3, 2010 12:05:08 PM
)
Syntax
1{{ date_expression | date : format : timezone}}
1$filter('date')(date, format, timezone)
Param | Type | Details |
---|---|---|
date | Date Number string | Date is the date to format either as a Date object, a number of milliseconds (string or number), or an ISO 8601 datetime string (yyyy-MM-ddTHH:mm:ss.sssZ, yyyy-MM-ddTHH:mmZ, yyyy-MM-dd, yyyyMMddTHHmmssZ, etc.) |
format (optional) | string | Formatting rules. If not specified, mediumDate is used. |
timezone (optional) | string | Timezone to be used for formatting. It understands UTC/GMT and the continental US time zone abbreviations, but for general use, use a time zone offset, for example, '+0430' (4 hours, 30 minutes east of the Greenwich meridian) If not specified, the timezone of the browser will be used. |
The Date
filter has predefined elements to format the date.
Implementation of the Date
filter is the same as the implementation of number
and filter
. Let's implement a simple example:
1<span>{{1288323623006 | date:'medium'}}</span><br>
2<!--output : Oct 29, 2010 9:10:23 AM -->
3
4<span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
5<!--output : 2010-10-29 09:10:23 +0530 (date format with time zone)-->
6
7<span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
8<!--Output : 10/29/2010 @ 9:10AM (insert string/character inside date format as '@')-->
9
10<span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
11<!--Ouput : 10/29/2010 at 9:10AM (insert string/character inside date format as 'at')-->
Lower-case and Upper-case converts a string into lower-case and upper-case. Lower-case
1{{ lowercase_expression | lowercase}}
1$filter("lowercase")();
For Example:
1<html ng-app="myApp">
2 <body ng-controller="myCtrl">
3 <!--this will convert text into lowercase-->
4 <p>Using HTML : {{"HTML CODE TO CONVERT INTO LOWERCASE" | lowercase}}</p>
5 </body>
6</html>
7<!--OutPut : html code to convert into lowercase-->
Upper Case
1{{ uppercase_expression | uppercase}}
1$filter("uppercase")();
For Example
1<html ng-app="myApp">
2 <body ng-controller="myCtrl">
3 <!--this will convert text into uppercase-->
4 <p>Using HTML : {{"html code to convert into upper case" | uppercase}}</p>
5 </body>
6</html>
7<!--OutPut : HTML CODE TO CONVERT INTO UPPER CASE-->
The limitTo filter returns a new array as a subset limited to the 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. If a number is used as the input tag, that number is converted into a string value.
Syntax
1{{ limitTo_expression | limitTo : limit : begin}}
1$filter('limitTo')(input, limit, begin)
input
is the source array, number, or string which has to be limited.limit
is the desired length of the subset array, string, or number.limitTo
will create a subset by copying from the beginning of the source (array or string).limit
is negative, limitTo
will create a subset by copying from the end of the source (array or string) are copied.array.length
. If limit
is undefined, the system will return the unchanged input array.Let's see an example:
1<!-- ng-app - attach an application module to the page -->
2<html ng-app="myApp">
3
4<!-- ng-controller - attach a controller functions to the page -->
5<body ng-controller="myCtrl">
6
7<!-- ng-init - to initialize "friends" as an array -->
8<div ng-init="friends = [
9 {name : 'John', phone : '89765', age : 34},
10 {name : 'Bob', phone : '32722', age : 28},
11 {name : 'Jake', phone : '87865', age : 30},
12 {name : 'Pop', phone : '67547', age : 26},
13 ]">
14</div>
15
16<table>
17 <tr>
18 <th>Name</th>
19 <th>Phone</th>
20 <th>Age</th>
21 </tr>
22 <!-- filter based on value of limitTo -->
23 <tr ng-repeat="f in friends | limitTo : 2">
24 <td>{{f.name}}</td>
25 <td>{{f.phone}}</td>
26 <td>{{f.age}}</td>
27 </tr>
28</table>
29
30</body>
31</html>
32
33<!--output shows only 2 records because we restricted limitTo to just 2
34Name Phone Age
35John 89765 34
36Bob 32722 28
37-->
OrderBy specifies an order to an array by expression. Strings are ordered alphabetically. Numbers are ordered numerically.
Syntax
1{{ orderBy_expression | orderBy : expression : reverse}}
1$filter("orderBy")(array, expression, reverse);
array
is the array to be sorted.expression
is the expression on which comparator predicts the order of element.reverse
is the element order.
The minus sign (-
) will denote descending order. See the below example:
1<!-- ng-app - attech an application module to the page -->
2<html ng-app="myApp">
3
4<!-- ng-controller - attech a controller functions to the page -->
5<body ng-controller="myCtrl">
6
7<!-- ng-init to initialize friends as an array -->
8<div ng-init="friends = [
9 {name : 'John', phone : '89765', age : 34},
10 {name : 'Bob', phone : '32722', age : 28},
11 {name : 'Jake', phone : '87865', age : 30},
12 {name : 'Pop', phone : '67547', age : 26},
13 ]">
14</div>
15
16<table>
17 <tr>
18 <th>Name</th>
19 <th>Phone</th>
20 <th>Age</th>
21 </tr>
22 <!-- Order by ascending order based on value of age -->
23 <tr ng-repeat="f in friends | orderBy : 'age'">
24 <td>{{f.name}}</td>
25 <td>{{f.phone}}</td>
26 <td>{{f.age}}</td>
27 </tr>
28</table>
29<br>
30<table>
31 <tr>
32 <th>Name</th>
33 <th>Phone</th>
34 <th>Age</th>
35 </tr>
36 <!-- Order by descending order based on value of age -->
37 <tr ng-repeat="f in friends | orderBy : '-age'">
38 <td>{{f.name}}</td>
39 <td>{{f.phone}}</td>
40 <td>{{f.age}}</td>
41 </tr>
42</table>
43
44</body>
45</html>
These are the Filter Components provided by Angular and how we use them. If you found this guide helpful, please hit the "thumbs up" button at the top right.