Pluralsight Logo
Author avatar

Gaurav Bhavsar

Author badge Author

Filter Components in AngularJS

Gaurav Bhavsar

Author BadgeAuthor
  • Aug 15, 2018
  • 18 Min read
  • 22,646 Views
  • Aug 15, 2018
  • 18 Min read
  • 22,646 Views
Front-End JavaScript
AngularJS

Introduction

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:

  • Filter
  • Currency
  • Number
  • Date
  • Lower-case/Upper-case
  • limitTo
  • orderBy

Filter Component

Angular provides filter components for filtering, organizing, and arranging the values based on input requirements.

Filter

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

  • HTML Template:
1
{{ filter_expression | filter : expression : comparator}}
  • JavaScript:
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!-- ng-app - attech an application module to the page -->
<html ng-app="myApp">

<!-- ng-controller - attech a controller functions to the page -->
<body ng-controller="myCtrl">
<!-- ng-init to initialize products as an array -->
<div ng-init="products = [{ name : 'sony', price : 23, quantity : 4},
                          { name : 'nokia', price : 45.3, quantity : 3},
                          { name : 'samsung', price : 65, quantity : 6},
                          { name : 'motorola', price : 12.7, quantity : 8},
                          { name : 'micromax', price : 39.75, quantity : 3},
                          { name : 'lenovo', price : 10, quantity : 2}]">
</div>

<!-- input filed to type expression to be filter -->
<div>
    <label>Search</label>
    <input ng-model="searchText" class="form-control" />
</div>

<table class="table">
    <tbody>
        <tr>
            <th>Name</th>
            <th>Price</th>
            <th>Quantity</th>
        </tr>
        <!-- filter based on value of searchText -->
        <tr ng-repeat="p in products | filter:searchText">
            <td>{{p.name}}</td>
            <td>{{p.price}}</td>
            <td>{{p.quantity}}</td>
        </tr>
    </tbody>
</table>

</body>
<html>

In the example, products is an actual array that shows a set of filtered values based on the input, "searchText".

Source Code:

Plunker for filter in HTML Template.

Explanation with Example (filter in JavaScript):

controller.js file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// register myCtrl to the angular module app.
app.controller("myCtrl", function($scope, $filter) {
  // create an array as $scope.products
  $scope.products = [
    { name: "sony", price: 23, quantity: 4 },
    { name: "nokia", price: 45.3, quantity: 3 },
    { name: "samsung", price: 65, quantity: 6 },
    { name: "motorola", price: 12.7, quantity: 8 },
    { name: "micromax", price: 39.75, quantity: 3 },
    { name: "lenovo", price: 10, quantity: 2 }
  ];

  // create a mirror copy of actual array
  $scope.mirrorProducts = angular.copy($scope.products);

  // bind function to ng-keyup event.
  $scope.filterFunc = function() {
    // override the value of mirrorProduct with filtered value
    $scope.mirrorProducts = $filter("filter")($scope.products, {
      $: $scope.searchText
    });
  };
});

index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<body ng-controller="myCtrl">
    <div class="form-group col-lg-10">
        <label class="label label-default" style="margin-left:10px">Search</label>
        <input ng-model="searchText" class="form-control" ng-keyup="filterFunc()" />
    </div>

    <table class="table">
        <tbody>
          <tr>
            <th>Name</th>
            <th>Price</th>
            <th>Quantity</th>
          </tr>
          <!-- use mirrorProducts array to display changes because we are overriding the mirrorProducts array with the original products array every time -->
          <tr ng-repeat="p in mirrorProducts">
            <td>{{p.name}}</td>
            <td>{{p.price}}</td>
            <td>{{p.quantity}}</td>
          </tr>
        </tbody>
    </table>
</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.

Source Code:

Plunker for filter in JavaScript

Currency

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
2
3
4
5
6
7
8
<p>{{25 | currency }}</p>
<!-- This will print result as $25.00. Note that the default fractionSize is 2. -->

<p>{{25 | currency : "₹" }}</p>
<!--This will print result as ₹25.00. -->

<p>{{25.46 | currency : "₹" : 4}}</p>
<!--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
2
3
4
5
6
7
8
<!--JS code-->
$scope.price = $filter('currency')(25);

<!--html code-->
<p>{{price}}</p>

<!--output-->
$25.00

Currency Format with Custom Symbol:

1
2
3
4
5
6
7
8
<!--JS code-->
$scope.price = $filter('currency')(25,'₹');

<!--html code-->
<p>{{price}}</p>

<!--Output-->
₹25.00

Currency Format with Custom Decimal Points:

1
2
3
4
5
6
7
8
<!--JS code-->
$scope.price = $filter('currency')(25,'₹',4);

<!---Html Code-->
<p>{{price}}</p>

<!--Output-->
₹25.0000

see Plunker for more examples.

Number

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
2
3
4
5
6
7
8
<p>{{24.76 | number}}</p>
<!--this will print result as 24.76-->

<p>{{24.76 | number : 0}}</p>
<!--this will print the result as 24-->

<p>{{24.76 | number : 1}}</p>
<!--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
2
3
4
5
6
7
8
$scope.number = $filter("number")(25.76);
// this will print a result as 25.76

$scope.number = $filter("number")((25.76: 0));
//this will print a result as 25

$scope.number = $filter("number")((25.76: 1));
//this will print a result as 25.8

see Plunker for more.

Date

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

  • In HTML Template Binding
1
{{ date_expression | date : format : timezone}}
  • In JavaScript
1
$filter('date')(date, format, timezone)

Explanation:

ParamTypeDetails
dateDate Number stringDate 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)stringFormatting rules. If not specified, mediumDate is used.
timezone (optional)stringTimezone 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
2
3
4
5
6
7
8
9
10
11
<span>{{1288323623006 | date:'medium'}}</span><br>
<!--output : Oct 29, 2010 9:10:23 AM -->

<span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
<!--output : 2010-10-29 09:10:23 +0530 (date format with time zone)-->

<span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
<!--Output : 10/29/2010 @ 9:10AM (insert string/character inside date format as '@')-->

<span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
<!--Ouput : 10/29/2010 at 9:10AM (insert string/character inside date format as 'at')-->

Lower-case/Upper-case

Lower-case and Upper-case converts a string into lower-case and upper-case. Lower-case

  • In HTML Template Binding
1
{{ lowercase_expression | lowercase}}
  • In JavaScript
1
$filter("lowercase")();

For Example:

1
2
3
4
5
6
7
<html ng-app="myApp">
  <body ng-controller="myCtrl">
      <!--this will convert text into lowercase-->
      <p>Using HTML : {{"HTML CODE TO CONVERT INTO LOWERCASE" | lowercase}}</p>
  </body>
</html>
<!--OutPut : html code to convert into lowercase-->

Upper Case

  • In HTML Template Binding
1
{{ uppercase_expression | uppercase}}
  • In JavaScript
1
$filter("uppercase")();

For Example

1
2
3
4
5
6
7
<html ng-app="myApp">
    <body ng-controller="myCtrl">
        <!--this will convert text into uppercase-->
        <p>Using HTML : {{"html code to convert into upper case" | uppercase}}</p>
    </body>
</html>
<!--OutPut : HTML CODE TO CONVERT INTO UPPER CASE-->

LimitTo

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

  • In HTML Template Binding
1
{{ limitTo_expression | limitTo : limit : begin}}
  • In JavaScript
1
$filter('limitTo')(input, limit, begin)

Explanations

  • 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.
  • If the limit number is positive, limitTo will create a subset by copying from the beginning of the source (array or string).
  • If limit is negative, limitTo will create a subset by copying from the end of the source (array or string) are copied.
  • The limit will be truncated if it's more than array.length. If limit is undefined, the system will return the unchanged input array.

Let's see an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<!-- ng-app - attach an application module to the page -->
<html ng-app="myApp">

<!-- ng-controller - attach a controller functions to the page -->
<body ng-controller="myCtrl">

<!-- ng-init - to initialize "friends" as an array -->
<div ng-init="friends = [
                        {name : 'John', phone : '89765', age : 34},
                        {name : 'Bob', phone : '32722', age : 28},
                        {name : 'Jake', phone : '87865', age : 30},
                        {name : 'Pop', phone : '67547', age : 26},
                        ]">
</div>

<table>
    <tr>
        <th>Name</th>
        <th>Phone</th>
        <th>Age</th>
    </tr>
    <!-- filter based on value of limitTo -->
    <tr ng-repeat="f in friends | limitTo : 2">
        <td>{{f.name}}</td>
        <td>{{f.phone}}</td>
        <td>{{f.age}}</td>
    </tr>
</table>

</body>
</html>

<!--output shows only 2 records because we restricted limitTo to just 2
Name	Phone	Age
John	89765	34
Bob 	32722	28
-->

OrderBy

OrderBy specifies an order to an array by expression. Strings are ordered alphabetically. Numbers are ordered numerically.

Syntax

  • In HTML Template Binding
1
{{ orderBy_expression | orderBy : expression : reverse}}
  • In JavaScript
1
$filter("orderBy")(array, expression, reverse);

Explanation

  • 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
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    <!-- ng-app - attech an application module to the page -->
    <html ng-app="myApp">
    
    <!-- ng-controller - attech a controller functions to the page -->
    <body ng-controller="myCtrl">
    
    <!-- ng-init to initialize friends as an array -->
    <div ng-init="friends = [
                            {name : 'John', phone : '89765', age : 34},
                            {name : 'Bob', phone : '32722', age : 28},
                            {name : 'Jake', phone : '87865', age : 30},
                            {name : 'Pop', phone : '67547', age : 26},
                            ]">
    </div>
    
    <table>
        <tr>
            <th>Name</th>
            <th>Phone</th>
            <th>Age</th>
        </tr>
        <!-- Order by ascending order based on value of age -->
        <tr ng-repeat="f in friends | orderBy : 'age'">
            <td>{{f.name}}</td>
            <td>{{f.phone}}</td>
            <td>{{f.age}}</td>
        </tr>
    </table>
    <br>
    <table>
        <tr>
            <th>Name</th>
            <th>Phone</th>
            <th>Age</th>
        </tr>
        <!-- Order by descending order based on value of age -->
        <tr ng-repeat="f in friends | orderBy : '-age'">
            <td>{{f.name}}</td>
            <td>{{f.phone}}</td>
            <td>{{f.age}}</td>
        </tr>
    </table>
    
    </body>
    </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.

5