Angular.js

AngularJS Autocomplete Example

For years, Autocomplete is a common UX pattern. In this basic example, developers will learn what AngularJS is and how to create an Autocomplete textbox by using the angular Library.

1. Introduction

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 AngularJS, let us see what are the important parts of an AngularJS application.

1.1.1 Templates

In AngularJS, 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 AngularJS to attach a specific behavior to that DOM element or even transform the DOM element and its children. Most of the directives in AngularJS library starts with the ng. The directives consist of the following parts:

  • 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 Why should we use AngularJS?

Using the Model-View-Controller architecture, the framework separates a web application into a simple and yet manageable structure, which comprises of “views”, “models” and “controllers”. The AngularJS library provides the in-build directives (or attributes) to extend the HTML inside a web page. When developers attach these directives to the HTML elements and attributes, it creates a dynamic web-page with very little coding.

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’s see how to create an autocomplete textbox in AngularJS.

2. AngularJS Autocomplete Example

Here is a step-by-step guide for implementing the Autocomplete feature in AngularJS.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven.

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 demonstrate on 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 input 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>AngularJsAutocomplete</groupId>
	<artifactId>AngularJsAutocomplete</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 implementing an Autocomplete feature in AngularJS.

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 <ng-app> directive.

index.jsp

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

3.3 Define a Model

In this step, we’ll define a model <country> using <ng-model> directive.

index.jsp

<input type="text" name="country" id="country" ng-model="country" ng-keyup="cname(country)" placeholder="Search country" class="form-control" />

3.4 Creating an AngularJS Controller

The JavaScript file i.e. country.js includes the CountryController function as the “controller” in the Model-View-Controller. This JavaScript code has all country names stored in an array format. We execute an angular function on the <ng-keyup> directive i.e. when a user types a word in the textbox then this function will search for the country name according to the letter. Later using the angular directive we are showing that filtered country list under the HTML tag.

country.js

var app = angular.module("myApp", []);

app.controller("CountryController", function($scope) {
	$scope.countryList = [
	                      "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegowina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", "Congo, the Democratic Republic of the", "Cook Islands", "Costa Rica", "Cote d'Ivoire", "Croatia (Hrvatska)", "Cuba", "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Falkland Islands (Malvinas)", "Faroe Islands", "Fiji", "Finland", "France", "France Metropolitan", "French Guiana", "French Polynesia", "French Southern Territories", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Heard and Mc Donald Islands", "Holy See (Vatican City State)", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran (Islamic Republic of)", "Iraq", "Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea, Democratic People's Republic of", "Korea, Republic of", "Kuwait", "Kyrgyzstan", "Lao, People's Democratic Republic", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein", "Lithuania", "Luxembourg", "Macau", "Macedonia, The Former Yugoslav Republic of", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia, Federated States of", "Moldova, Republic of", "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn", "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania", "Russian Federation", "Rwanda", "Saint Kitts and Nevis", "Saint Lucia", "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Seychelles", "Sierra Leone", "Singapore", "Slovakia (Slovak Republic)", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "Spain", "Sri Lanka", "St. Helena", "St. Pierre and Miquelon", "Sudan", "Suriname", "Svalbard and Jan Mayen Islands", "Swaziland", "Sweden", "Switzerland", "Syrian Arab Republic", "Taiwan, Province of China", "Tajikistan", "Tanzania, United Republic of", "Thailand", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela", "Vietnam", "Virgin Islands (British)", "Virgin Islands (U.S.)", "Wallis and Futuna Islands", "Western Sahara", "Yemen", "Yugoslavia", "Zambia", "Zimbabwe"
	                      ];
	$scope.cname = function(string) {
		$scope.hidethis = false;
		var output = [];
		angular.forEach($scope.countryList, function(country) {
			if (country.toLowerCase().indexOf(string.toLowerCase()) >= 0) {
				output.push(country);
			}
		});
		$scope.filterCountry = output;
	};
	$scope.fillInputBox = function(string) {
		$scope.country = string;
		$scope.hidethis = true;
	};
});

3.5 Bind the Model

In this step, we are using the <ng-repeat> directive to display the filtered country list under the textbox.

index.jsp

<ul class="list-group" ng-hide="hidethis">
   <li class="list-group-item" ng-repeat="country_info in filterCountry" ng-click="fillInputBox(country_info)">{{country_info}}</li>
</ul>

3.6 Complete Application

Complete the above steps and save the file.

index.jsp

<<!DOCTYPE html>
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>AngularJS Autocomplete</title>
      
      <!-- AngularJs Javascript File -->
      <script type="text/javascript" src="resource/js/angular_v1.6.0.js"></script>
      <script type="text/javascript" src="resource/js/country.js"></script>	
      
      <!-- Bootstrap Css -->
      <link rel="stylesheet" href="https://www.webcodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9tYXhjZG4uYm9vdHN0cmFwY2RuLmNvbS8=bootstrap/3.3.7/css/bootstrap.min.css">
      
      <style type="text/css">
      	li {
      		cursor: pointer;  
        }
        
        li:hover {
         	background-color: #f9f9f9;  
        }
      </style>
   </head>
   <body>
      <div id="angularAutocomplete" class="container">
         <h1 align="center" class="text-primary">AngularJS - AutoComplete Textbox</h1>
         <hr />
         <div ng-app="myApp" ng-controller="CountryController">
            <label for="country" class="text-secondary">Enter Country Name</label>       
            <input type="text" name="country" id="country" ng-model="country" ng-keyup="cname(country)" placeholder="Search country" class="form-control" />  
            <ul class="list-group" ng-hide="hidethis">
               <li class="list-group-item" ng-repeat="country_info in filterCountry" ng-click="fillInputBox(country_info)">{{country_info}}</li>
            </ul>
            <div> </div>
            <p id="pText" class="text-info">You Selected <strong>{{ country }}</strong></p>
         </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 (i.e. the welcome page) will be displayed.

http://localhost:8085/AngularJsAutocomplete/

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

Fig. 7: Welcome page
Fig. 7: Welcome page

Enter the letters and the filtered country list will be displayed under the text-box as below.

Fig. 8: Search a Country
Fig. 8: Search a Country

After selecting the country, the name will be displayed as below.

Fig. 9: Selected Country
Fig. 9: Selected Country

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

6. Conclusion

In this section, developers learned how to do an Autocomplete using the Angular library. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was an example of Autocomplete feature in AngularJS.

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

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