Angular.js

AngularJS Controllers Example

Hello readers, controller in the angular library is a JavaScript function that controls the flow of an application data in the angular application. In this tutorial, we will see how the controller works in 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. But before we start creating a real application using the angular library, let us see what the important parts of an angular application are.

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 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 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 support 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 Controllers in Angular?

Controllers in the angular library are used to support the data and the behavior of an angular web application. In HTML, the angular controller is defined using the ng-controller directive. This tag adds the other functionalities to the scope of the view and here is what the syntax will look like.

Angular Controller Syntax

var mainApp = angular.module('myApp', []);

mainApp.controller('myCtrl', function($scope) {
    $scope.msg = " Hello World!";
});

The controller in angular applications basically acts as a bridge between the model and the view components and do the following important responsibilities.

    • Sharing the static or the dynamic results to the application view
    • Handling the user input elements such as button clicks, input text validation etc.
    • Processing the user’s input and managing the presentation logic
Fig. 1: Logical representation of Angular Controller
Fig. 1: Logical representation of Angular Controller

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 controller using the angular library.

2. AngularJS Controllers Example

Here is a step-by-step guide for implementing the controllers in the angular web 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. 2: Application Project Structure
Fig. 2: 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. 3: Create Maven Project
Fig. 3: 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. 4: Project Details
Fig. 4: Project Details

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

Fig. 5: Archetype Selection
Fig. 5: 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. 6: Archetype Parameters
Fig. 6: 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>AngularJsController</groupId>
	<artifactId>AngularJsController</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
</project>

3. Application Building

Let’s start building an application to understand the basic building blocks of the controllers in the angular library.

3.1 Load the Angular 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 Angular application

Next, we will define the angular application using the <ng-app> and <ng-controller> directives.

index.jsp

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

3.3 Define the Angular Controller

The JavaScript file i.e. country.js includes the myCtrl function as the “controller” in the Model-View-Controller. This JavaScript code has the random country names stored in an array format and the add() function that binds the text-box result to the view. Do note, the angular function will be executed on the $scope objects through a button click.

country.js

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

mainApp.controller('myCtrl', function($scope) {
	$scope.countryList = ["Ireland", "Portugal", "Thailand", "Belarus"];

	$scope.add = function() {
		$scope.countryList.push($scope.c_name);
		$scope.c_name = "";
	}
});

3.4 Complete Application

In this example, we have defined the <ng-repeat> directive to display the country list under the text-box. Complete the above steps to understand the usage of the angular controller with real-life practices.

index.jsp

<!DOCTYPE html>
<html>
 <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>AngularJS Controller Example</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/4.0.0/css/bootstrap.min.css">
    
    <style type="text/css">
    	.width {
    		width: 1070px !important;
    	}
    </style>
 </head>
 <body>
    <div id="angularController" class="container width">
       <h1 align="center" class="text-primary">AngularJS - Controller Example</h1>
       <hr />
       
       <!------ ANGULAR CONTROLLER EXAMPLE ------>
       <div ng-app="myApp" ng-controller="myCtrl">
          <div class="input-group">             
             <input id="cName" type="text" class="form-control" ng-model="c_name" placeholder="Enter Country Name ..." />
             <span class="input-group-btn">
             	<button id="cBtn" type="button" class="btn btn-primary" ng-click="add()">Add</button>
             </span>
          </div>
          
          <!------ COUNTRY LIST ------>
          <div> </div>
          <h3 class="text-success">Country List</h3>
          <ul class="list-group">
             <li class="list-group-item font-weight-light" ng-repeat="c_list in countryList">{{ c_list }}</li>
          </ul>
       </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 tomcat server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server.

Fig. 7: How to Deploy Application on Tomcat
Fig. 7: 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 having the default country list will be displayed.

http://localhost:8080/AngularJsController/

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

Fig. 8: Default country list
Fig. 8: Default country list

Here we have the add() function attached to a button click. This angular function will add a new country name to the display list as shown below.

Fig. 9: Updated country list
Fig. 9: Updated country list

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

6. Conclusion

In this section, developers learned how to create a simple controller 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 controllers in the angular library.

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

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
Inline Feedbacks
View all comments
Back to top button