Angular.js

AngularJS Directives Example

Hello readers, in this basic example, developers will learn what AngularJS is and how to use the angular directives 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 AngularJS, let us see the important parts of an angular 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 prefix ng. Below is the list of the 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-init: The ng-init directive defines the initial values for an angular application
  • 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-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-bind: The ng-bind directive binds the AngularJS application data to the HTML tags
  • ng-repeat: The ng-repeat directive repeat a set of HTML elements for each item in a given collection
  • ng-show: The ng-show directive hides or shows the HTML elements
  • ng-readonly: The ng-readonly directive makes an HTML element as read-only based on the boolean value of the specified expression
  • ng-disabled: The ng-disabled directive makes an HTML element as disabled based on the boolean value of the specified expression
  • ng-if: The ng-if directive removes an HTML based on the boolean value of the specified expression. Here if an expression returns true then the HTML element is re-created otherwise the element is removed from the HTML document
  • ng-click: The ng-if directive specifies a behavior when an HTML element is clicked

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 angular 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 us create a simple application using the important angular directives.

2. AngularJS Directives Example

Here is a step-by-step guide to implementing the Angular Directives.

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>AngularJsDirectives</groupId>
	<artifactId>AngularJsDirectives</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 directives.

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 = "">
 ...
</div>

3.3 Define Directives

In angular, Directives are the powerful components that help to extend the basic HTMLelements/attributes. In this step, we’ll define the angular directives to show their usage in the angular applications.

index.jsp

<!-- EXAMPLE 1 -->
<div id="model">
	<input type="text" name="name" id="text_name" ng-model="name" placeholder="Enter your name" class="form-control" />
	<div> </div>
	<p id="nText" class="text-info">Your Name is <strong>{{ name }}</strong></p>
</div>

<!-- EXAMPLE 2 -->
<div id="init_repeat" ng-init="days=['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']">
	<h2 id="wText" class="text-secondary">7 Days of the Weeks</h2>
	<ul class="list-group">
		<li class="list-group-item" ng-repeat="dname in days">{{ dname }}</li>
	</ul>
</div>

<!-- EXAMPLE 3 -->
<div id="bind">
	<input type="text" name="cname" id="country_name" ng-model="cname" placeholder="Enter country" class="form-control" />
	<div> </div>
	<p id="cText" class="text-info">Country name is <strong><span ng-bind="cname"></span></strong></p>
</div>

<!-- EXAMPLE 4 -->
<div id="disabled" ng-init="switch=true">
	<button id="btn" class="btn btn-default" ng-disabled="switch">Click Me!</button>	
	<input type="checkbox" name="switch" id="checkBox" ng-model="switch" value="Button"/>
	<div> </div>
	<p id="dText" class="text-dark">Disabled - <strong>{{ switch }}</strong></p>
</div>

3.4 Complete Application

Complete the above steps and I will show you how to use the angular directives 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 Directives</title>
      
      <!-- AngularJs Javascript File -->
      <script type="text/javascript" src="resource/js/angular_v1.6.0.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">          
   </head>
   <body>
      <div id="angularJsDirectives" class="container">
         <h1 align="center" class="text-primary">AngularJS - Directives Example</h1>
         <hr />
         <div ng-app="">
         	<!-- EXAMPLE 1 -->
         	<h3 class="text-warning"><ins>ng-model</ins></h3>
         	<div id="model">
				<input type="text" name="name" id="text_name" ng-model="name" placeholder="Enter your name" class="form-control" />
				<div> </div>
				<p id="nText" class="text-info">Your Name is <strong>{{ name }}</strong></p>
			</div>
			
         	<!-- EXAMPLE 2 -->
         	<h3 class="text-warning"><ins>ng-init</ins> & <ins>ng-repeat</ins></h3>
         	<div id="init_repeat" ng-init="days=['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']">
         		<h2 id="wText" class="text-secondary">7 Days of the Weeks</h2>				
				<ul class="list-group">
					<li class="list-group-item" ng-repeat="dname in days">{{ dname }}</li>
				</ul>
			</div>
			
			<!-- EXAMPLE 3 -->
			<h3 class="text-warning"><ins>ng-bind</ins></h3>
			<div id="bind">
				<input type="text" name="cname" id="country_name" ng-model="cname" placeholder="Enter country" class="form-control" />
				<div> </div>
				<p id="cText" class="text-info">Country name is <strong><span ng-bind="cname"></span></strong></p>
			</div>
			
			<!-- EXAMPLE 4 -->
			<h3 class="text-warning"><ins>ng-disabled</ins></h3>
			<div id="disabled" ng-init="switch=true">
				<button id="btn" class="btn btn-default" ng-disabled="switch">Click Me!</button>	
				<input type="checkbox" name="switch" id="checkBox" ng-model="switch" value="Button"/>
				<div> </div>
				<p id="dText" class="text-dark">Disabled - <strong>{{ switch }}</strong></p>
			</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 directives will be displayed.

http://localhost:8085/AngularJsDirectives/

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

Fig. 7: Angular Directives
Fig. 7: Angular Directives

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

6. Conclusion

In this section, developers learned how to create a simple application using the AngularJS Directives. 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 Directives in the AngularJS framework.

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

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