Angular.js

AngularJS Filters Example

Hello readers, in this basic example, developers will learn what AngularJS is and how to use the angular filters in the angular applications.

1. Introduction

1.1 What is AngularJS?

AngularJS is a JavaScript MVC or Model-View-Controller framework developed by Google that lets developers build well structured, easily testable, and maintainable front-end applications. Before we start with the creation of a real application using the angular framework, let us see the important parts of an angular application.

1.1.1 Templates

In angular, a template is an HTML with added markups. AngularJS library compiles the templates and renders the resultant HTML page.

1.1.2 Directives

Directives are the markers (i.e. attributes) on a DOM element that tell angular to attach a specific behavior to that DOM element or even transform the DOM element and its children. Most of the directives in the angular library start with the prefix ng. Below is the list of important directives that are available in the angular library.

  • ng-app: The ng-app directive is a starting point. If the AngularJS framework finds the ng-app directive anywhere in the HTML document, it bootstraps (i.e. initializes) itself and compiles the HTML template
  • ng-model: The ng-model directive binds an HTML element to a property on the $scope object. It also binds the values of AngularJS application data to the HTML input controls.
  • ng-bind: The ng-bind directive binds the AngularJS application data to the HTML tags
  • ng-controller: The ng-controller directive specifies a controller in the HTML element. This controller will add behavior or maintain the data in that HTML element and its child elements
  • ng-repeat: The ng-repeat directive repeat a set of HTML elements for each item in a given collection

1.1.3 Expressions

An expression is like a JavaScript code usually wrapped inside the double curly braces such as {{ expression }}. AngularJS library evaluates the expression and produces a result.

1.2 What are Angular filters?

In an angular library, filters allow transforming the data to be displayed on the UI without changing the original format. Angular filters are implemented in the angular directives and expressions using the pipe | character. Following is the basic syntax using the angular filter in an angular application.

Angular filter basic syntax

{{ expression | filterName:parameter }}

The angular library provides various filters to change the data and the below list shows the important filters.

1.2.1 Currency Filter

This filter converts a number into a specified currency format and symbol. By default, angular library shows $ as a currency symbol, but this can be changed according to the application need. Following is the syntax of using the currency filter in angular applications.

Syntax

{{ currency_expression | currency : 'currency_symbol' : 'fraction' }}

Do note, currency_symbol and fraction are two optional limits where currency_symbol decides the symbol of the currency and fraction decides the number of decimal points.

1.2.2 Uppercase Filter

This filter converts the string to the uppercase format. Following is the syntax of using the uppercase filter in angular applications.

Syntax

{{ data_string | uppercase }}

1.2.3 Lowercase Filter

This filter converts the uppercase string to the lowercase format. Following is the syntax of using the lowercase filter in angular applications.

Syntax

{{ data_string | lowercase }}

1.2.4 Filter

This filter selects items from an array based on the specified criteria and returns the matching output in the form of an array. Following is the syntax of using the filter in angular applications.

Syntax

{{ filter_expression | filter : filter_criteria }}

1.2.5 Order-by Filter

This filter sorts an array according to the specified condition, e.g. ascending or descending. Following is the syntax of using the orderBy filter in angular applications.

Syntax

{{ orderBy_expression | orderBy : predicate_expression : reverse }}

1.2.6 Limit-to Filter

This filter is used to create an array of specified elements or a string containing a specific number of elements. The number or character are taken from the beginning or the end of the element. Following is the syntax of using the limitTo filter in angular applications.

Syntax

{{ data_tolimit | limitTo : limit : begin }}

1.2.7 Date Filter

This filter formats the date into a string based on the given format. Following is the syntax of using the date filter in angular applications.

Syntax

{{ date_expression | date : format : timezone }}

These new APIs make developer’s life easier, really! But it would be difficult for a beginner to understand this without an example. Therefore, let us create a simple application using the important angular filters.

2. AngularJS Filters Example

Here is a step-by-step guide for implementing the filters in angular applications.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure if you are confused about where you should create the corresponding files or folder later!

Fig. 1: Application Project Structure
Fig. 1: Application Project Structure

2.3 Project Creation

This section will show how to create a Java-based Maven project with Eclipse. In Eclipse Ide, go to File -> New -> Maven Project.

Fig. 2: Create Maven Project
Fig. 2: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.

Fig. 3: Project Details
Fig. 3: Project Details

Select the ‘Maven Web App’ Archetype from the list of options and click next.

Fig. 4: Archetype Selection
Fig. 4: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will enter the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 5: Archetype Parameters
Fig. 5: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you see, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>AngularJsFilters</groupId>
	<artifactId>AngularJsFilters</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
</project>

Let’s start building the application!

3. Application Building

Let’s create an application to understand the basic building blocks of the angular filters.

3.1 Load the AngularJS framework

Since it is a pure JavaScript framework, we should add its reference using the <script> tag.

<script type="text/javascript" src="resource/js/angular_v1.6.0.js"></script>

3.2 Define the AngularJS application

Next, we will define the AngularJS application using the <ng-app> directive.

index.jsp

<div ng-app = "myApp">
 ...
</div>

3.3 Define Filters

In angular, filters are the powerful components that help to modify the data. In this step, we’ll define the angular filters to show their usage in the angular applications.

index.jsp

<!----- EXAMPLE #1 - ANGULAR CODE FOR CURRENCY FILTER ----->
<div id="currencyFilter" class="non default">
 <div class="login">
	<h3 align="center" class="text-primary">Currency Filter</h3>
	<hr/>
	<p class="text-info"><strong>Enter price</strong></p>
	<input type="text" name="price" id="entered_price" ng-model="price" placeholder="Enter price" class="form-control" />
	<div> </div>
	<p class="text-success"><strong>Output : </strong>{{ price|currency }}</p>
 </div>
</div>

<!----- EXAMPLE #2 - ANGULAR CODE FOR UPPERCASE FILTER ----->
<div id="uppercaseFilter" class="non" style="display: none">
 <div class="login">
	<h3 align="center" class="text-primary">Uppercase Filter</h3>
	<hr/>
	<p class="text-info"><strong>Enter a string</strong></p>
	<input type="text" name="uname" id="uppercase_name" ng-model="uname" placeholder="Enter name in uppercase" class="form-control" />
	<div> </div>
	<p class="text-success"><strong>Output : </strong>{{ uname|uppercase }}</p>
 </div>
</div>

<!----- EXAMPLE #3 - ANGULAR CODE FOR LOWERCASE FILTER ----->
<div id="lowcaseFilter" class="non" style="display: none">
 <div class="login">
	<h3 align="center" class="text-primary">Lowercase Filter</h3>
	<hr/>
	<p class="text-info"><strong>Enter a string</strong></p>
	<input type="text" name="lname" id="lowercase_name" ng-model="lname" placeholder="Enter name in lowercase" class="form-control" />
	<div> </div>
	<p class="text-success"><strong>Output : </strong>{{ lname|lowercase }}</p>
 </div>
</div>

<!----- EXAMPLE #4 - ANGULAR CODE FOR CUSTOM FILTER ----->
<div ng-controller = "fetchFriends">
 <div id="customfilter" class="non" style="display: none">
	<div class="login">
	   <h3 align="center" class="text-primary">Filter</h3>
	   <hr/>
	   <p class="text-info"><strong>Search by Name</strong></p>
	   <input type="text" name="fname" id="friend_name" ng-model="fname" placeholder="Enter a string" class="form-control" />
	   <!----- FILTER RECORDS BY NAME ----->
	   <div> </div>
	   <ul class="friend_info">
		  <li class="left info_heading">Name</li>
		  <li class="right info_heading">Age</li>
		  <li class="text-success" ng-repeat="f in friends|filter:{name:fname}" >
			 <div id="fName" class="left">{{ f.name }}</div>
			 <div id="fAge" class="right">{{ f.age }}</div>
		  </li>
	   </ul>
	   <div> </div>
	   <p class="text-info"><strong>Search by Age</strong></p>
	   <input type="text" name="fage" id="friend_age" ng-model="fage" placeholder="Enter a number" class="form-control" />
	   <!----- FILTER RECORDS BY AGE ----->
	   <div> </div>
	   <ul class="friend_info">
		  <li class="left info_heading">Name</li>
		  <li class="right info_heading">Age</li>
		  <li class="text-success" ng-repeat="f in friends|filter:{age:fage}">
			 <div id="fName" class="left">{{ f.name }}</div>
			 <div id="fAge" class="right">{{ f.age }}</div>
		  </li>
	   </ul>
	</div>
 </div>
 
 <!----- EXAMPLE #5 - ANGULAR CODE FOR ORDER-BY FILTER ----->
 <div id="orderFilter" class="non" style="display: none">
	<div class="login">
	   <h3 align="center" class="text-primary">orderBy Filter</h3>
	   <hr/>
	   <p class="text-info"><strong>Select an option</strong></p>
	   <select ng-model="select">
		  <option value="" disabled selected>Select option</option>
		  <option value="name">Name</option>
		  <option value="age">Age</option>
	   </select>
	   <ul class="friend_info">
		  <li class="left info_heading">Name</li>
		  <li class="right info_heading">Age</li>
		  <li class="text-success" ng-repeat="f in friends|orderBy: select">
			 <div id="fName" class="left">{{ f.name }}</div>
			 <div id="fAge" class="right">{{ f.age }}</div>
		  </li>
	   </ul>
	</div>
 </div>
 
 <!----- EXAMPLE #6 - ANGULAR CODE FOR LIMIT-TO FILTER ----->
 <div id="limitToFilter" class="non" style="display: none">
	<div class="login">
		<h3 align="center" class="text-primary">limitTo Filter</h3>                          
		<hr/>
		<p class="text-info"><strong>Enter a string & length</strong></p>
		<input type="text" name="lmInput" id="limitTo_input" ng-model="lmInput" placeholder="Enter a name" class="form-control" />
		<div> </div>
		<input type="number" step="1" ng-model="LimitTo" value="2" placeholder="Enter length filter" class="limitTo form-control" />
		<div> </div>
		<p class="text-success"><strong>Output : </strong> {{ lmInput|limitTo:LimitTo }}</p>
	</div>
 </div>

3.4 Complete Application

Complete the above steps and I will show you how to use the angular filters with real-life practices. Let’s see the code snippet.

index.jsp

<!DOCTYPE html>
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>AngularJs Filters</title>
      
      <!-- jQuery & AngularJs Javascript File -->      
      <script type="text/javascript" src="resource/js/jquery-3.2.1.min.js"></script>
      <script type="text/javascript" src="resource/js/angular_v1.6.0.js"></script>
      <script type="text/javascript" src="resource/js/friends.js"></script>
      
      <!-- Bootstrap Css -->
      <link rel="stylesheet" type="text/css" href="resource/css/bootstrap.min.style.css">
      <link rel="stylesheet" type="text/css" href="https://www.webcodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9tYXhjZG4uYm9vdHN0cmFwY2RuLmNvbS8=bootstrap/3.3.7/css/bootstrap.min.css">
      
      <script type="text/javascript">      	 
         function reset(data) {
         	$('.non').css('display', 'none');
         	$('#' + data).css('display', 'block');
         	$('td.active').removeClass('active');
         	$('.' + data).addClass('active');         	
         }
      </script>
   </head>
   <body>
      <h1 align="center" class="text-primary h1FontStyle">AngularJs Filters Example</h1>
      <hr/>
      <div ng-app="myApp" class="container">
         <div class="demo-wrapper row">
            <!----- HTML TABLE TO DISPLAY THE ANGULARJS FILTER'S LIST ----->        
            <table class="col-md-3 col-md-offset-3 col-xs-12" border="1">
               <thead>
                  <tr><th><h3 align="center">Angular Filters</h3></th></tr>
               </thead>
               <tbody>
                  <tr><td class="currencyFilter active" id="activefilter" onclick="reset('currencyFilter');"><h4 class="text-muted">Currency</h4></td></tr>
                  <tr><td class="uppercaseFilter" onclick="reset('uppercaseFilter');"><h4 class="text-muted">Uppercase</h4></td></tr>
                  <tr><td class="lowcaseFilter" onclick="reset('lowcaseFilter');"><h4 class="text-muted">Lowercase</h4></td></tr>
                  <tr><td class="customfilter" onclick="reset('customfilter');"><h4 class="text-muted">Filter</h4></td></tr>
                  <tr><td class="orderFilter" onclick="reset('orderFilter');"><h4 class="text-muted">orderBy</h4></td></tr>
                  <tr><td class="limitToFilter" onclick="reset('limitToFilter');"><h4 class="text-muted">limitTo</h4></td></tr>
               </tbody>
            </table>
            <div class="col-md-4 col-md-offset-0 col-xs-12">
               <div id="angularJsFilters">               
                  <!----- EXAMPLE #1 - ANGULAR CODE FOR CURRENCY FILTER ----->
                  <div id="currencyFilter" class="non default">
                     <div class="login">
                        <h3 align="center" class="text-primary">Currency Filter</h3>
                        <hr/>
                        <p class="text-info"><strong>Enter price</strong></p>
                        <input type="text" name="price" id="entered_price" ng-model="price" placeholder="Enter price" class="form-control" />
                        <div> </div>
                        <p class="text-success"><strong>Output : </strong>{{ price|currency }}</p>
                     </div>
                  </div>
                  
                  <!----- EXAMPLE #2 - ANGULAR CODE FOR UPPERCASE FILTER ----->
                  <div id="uppercaseFilter" class="non" style="display: none">
                     <div class="login">
                        <h3 align="center" class="text-primary">Uppercase Filter</h3>
                        <hr/>
                        <p class="text-info"><strong>Enter a string</strong></p>
                        <input type="text" name="uname" id="uppercase_name" ng-model="uname" placeholder="Enter name in uppercase" class="form-control" />
                        <div> </div>
                        <p class="text-success"><strong>Output : </strong>{{ uname|uppercase }}</p>
                     </div>
                  </div>
                  
                  <!----- EXAMPLE #3 - ANGULAR CODE FOR LOWERCASE FILTER ----->
                  <div id="lowcaseFilter" class="non" style="display: none">
                     <div class="login">
                        <h3 align="center" class="text-primary">Lowercase Filter</h3>
                        <hr/>
                        <p class="text-info"><strong>Enter a string</strong></p>
                        <input type="text" name="lname" id="lowercase_name" ng-model="lname" placeholder="Enter name in lowercase" class="form-control" />
                        <div> </div>
                        <p class="text-success"><strong>Output : </strong>{{ lname|lowercase }}</p>
                     </div>
                  </div>
                  
                  <!----- EXAMPLE #4 - ANGULAR CODE FOR CUSTOM FILTER ----->
                  <div ng-controller = "fetchFriends">
                     <div id="customfilter" class="non" style="display: none">
                        <div class="login">
                           <h3 align="center" class="text-primary">Filter</h3>
                           <hr/>
                           <p class="text-info"><strong>Search by Name</strong></p>
                           <input type="text" name="fname" id="friend_name" ng-model="fname" placeholder="Enter a string" class="form-control" />
                           <!----- FILTER RECORDS BY NAME ----->
                           <div> </div>
                           <ul class="friend_info">
                              <li class="left info_heading">Name</li>
                              <li class="right info_heading">Age</li>
                              <li class="text-success" ng-repeat="f in friends|filter:{name:fname}" >
                                 <div id="fName" class="left">{{ f.name }}</div>
                                 <div id="fAge" class="right">{{ f.age }}</div>
                              </li>
                           </ul>
                           <div> </div>
                           <p class="text-info"><strong>Search by Age</strong></p>
                           <input type="text" name="fage" id="friend_age" ng-model="fage" placeholder="Enter a number" class="form-control" />
                           <!----- FILTER RECORDS BY AGE ----->
                           <div> </div>
                           <ul class="friend_info">
                              <li class="left info_heading">Name</li>
                              <li class="right info_heading">Age</li>
                              <li class="text-success" ng-repeat="f in friends|filter:{age:fage}">
                                 <div id="fName" class="left">{{ f.name }}</div>
                                 <div id="fAge" class="right">{{ f.age }}</div>
                              </li>
                           </ul>
                        </div>
                     </div>
                     
                     <!----- EXAMPLE #5 - ANGULAR CODE FOR ORDER-BY FILTER ----->
                     <div id="orderFilter" class="non" style="display: none">
                        <div class="login">
                           <h3 align="center" class="text-primary">orderBy Filter</h3>
                           <hr/>
                           <p class="text-info"><strong>Select an option</strong></p>
                           <select ng-model="select">
                              <option value="" disabled selected>Select option</option>
                              <option value="name">Name</option>
                              <option value="age">Age</option>
                           </select>
                           <ul class="friend_info">
                              <li class="left info_heading">Name</li>
                              <li class="right info_heading">Age</li>
                              <li class="text-success" ng-repeat="f in friends|orderBy: select">
                                 <div id="fName" class="left">{{ f.name }}</div>
                                 <div id="fAge" class="right">{{ f.age }}</div>
                              </li>
                           </ul>
                        </div>
                     </div>
                     
                     <!----- EXAMPLE #6 - ANGULAR CODE FOR LIMIT-TO FILTER ----->
                     <div id="limitToFilter" class="non" style="display: none">
                        <div class="login">
                        	<h3 align="center" class="text-primary">limitTo Filter</h3>                          
                            <hr/>
                            <p class="text-info"><strong>Enter a string & length</strong></p>
                            <input type="text" name="lmInput" id="limitTo_input" ng-model="lmInput" placeholder="Enter a name" class="form-control" />
                            <div> </div>
                            <input type="number" step="1" ng-model="LimitTo" value="2" placeholder="Enter length filter" class="limitTo form-control" />
                            <div> </div>
                            <p class="text-success"><strong>Output : </strong> {{ lmInput|limitTo:LimitTo }}</p>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </body>
</html>

4. Run the Application

As we are ready for all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server.

Fig. 6: How to Deploy Application on Tomcat
Fig. 6: How to Deploy Application on Tomcat

Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it in the browser.

5. Project Demo

Open your favorite browser and hit the following URL. The output page using the angular filters will be displayed.

http://localhost:8085/AngularJsFilters/

Server name (localhost) and port (8085) may vary as per your Tomcat configuration.

Fig. 7: Angular Filters
Fig. 7: Angular Filters

That’s all for this post. Happy Learning!!

6. Conclusion

In this section, developers learned how to create a simple application using the angular filters. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was an example of Angular Filter in the AngularJS framework.

Download
You can download the full source code of this example here: AngularJsFilters

Yatin

The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button