Angular.js

AngularJS Reset Form Fields Example

Hello readers, in this tutorial, developers will learn what AngularJS is and how to reset the form fields on a button click using the angular directives.

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 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.

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 ng-model, ng-click, and ng-disabled angular directives.

2. AngularJS Reset Form Fields Example

Here is a step-by-step guide for implementing this tutorial in the 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!

AngularJS Reset Form Fields - 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.

AngularJS Reset Form Fields - Maven Project
Fig. 2: Create a 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.

AngularJS Reset Form Fields - Project Details
Fig. 3: Project Details

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

AngularJS Reset Form Fields - 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.

AngularJS Reset Form Fields - 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>com.angular</groupId>
	<artifactId>AngularJsFormReset</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 this tutorial.

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 HTML form tag and different angular directives.

index.jsp

<div ng-app="app" ng-controller="myctrl">
	<form>
		….
	</form>
</div>

3.3 Define the JavaScript

This script will reset the form fields to its default values on a button click. Let’s see the sample code snippet.

form_reset.js

var app = angular.module("app", []);
app.controller("myctrl", function($scope) {

	$scope.person = {
			emailAddr: "daniel.atlas@webcodegeeks.com",
			userName: "daniel.atlas"
	};

	var orig = angular.copy($scope.person);

	$scope.resetForm = function() {
		$scope.person = angular.copy(orig);
		$scope.personForm.$setPristine();
	};

	$scope.isPersonChanged = function() {
		return !angular.equals($scope.person, orig);
	};
});

3.4 Complete Application

In this example, we will use the ng-click angular directive to reset the form data if it the field values are changed. Complete the above steps and I will show you how to implement this tutorial. Let’s see the sample code snippet.

index.jsp

<!DOCTYPE html>
<html>
	<head>
	    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	    <title>AngularJS Form Reset</title>
	
	    <!-- AngularJs Files -->
	    <script type="text/javascript" src="resource/js/angular_v1.6.0.js"></script>
	    <script type="text/javascript" src="resource/js/form_reset.js"></script>
	
	    <!-- Bootstrap Css -->
	    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
	
	    <style type="text/css">
	        input.ng-invalid {
	            border: 1px solid red;
	        }
	    </style>
	</head>
	<body>
	    <div id="angularFormReset" class="container">
	        <h1 align="center" class="text-primary">AngularJS - Reset Form Values Example</h1>
	        <hr />
	        
	        <div ng-app="app" ng-controller="myctrl">
	        	<!-- Person form. -->
	            <form name="personForm" novalidate>
	                <div id="email_address" class="form-group">
	                    <label for="email">Email address</label>
	                    <input type="email" class="form-control" id="email" name="emailAddr" ng-model="person.emailAddr" required />
	                </div>
	                <div id="user_name" class="form-group">
	                    <label for="username">Username</label>
	                    <input type="text" class="form-control" id="username" name="userName" ng-model="person.userName" required />
	                </div>
	                <div> </div>
	                <button type="button" class="btn btn-default" ng-click="resetForm()" ng-disabled="!isPersonChanged()">Reset</button>
	            </form>
				<div> </div>
				
				<!-- To display the updated boolean flag if the form-data is changed. -->
	            <div id="pristine_output">
	                <strong>personForm.$pristine</strong>= <span>{{ personForm.$pristine }}</span>
	            </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.

AngularJS Reset Form Fields - 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 will be displayed.

http://localhost:8082/AngularJsFormReset/

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

AngularJS Reset Form Fields - Application Output
Fig. 7: Application Output

If the form fields are changed, the Reset button will be enabled and the user can click on this button to reset the form data. That’s all for this post. Happy Learning!

6. Conclusion

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

7. Download the Eclipse Project

This was an example of resetting the form data using the HTML form tag and angular directives.

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

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