AngularJS: Routing

In any web application, navigation is crucial. If users can’t navigate through your application easily, you will quickly lose them. AngularJS provides an out of the box service provider called $routeProvider. Through AngularJS, developers can use routes to create different URLs for different content in an application.

As mentioned in the documentation, the routing functionality in Angular is due to the ngRoute module, which is distributed separately from the core Angular framework. The application’s module needs to declare this dependency in order to use the features provided by the ngRoute module. Through this post, we will learn how to implement routing using AngularJS.

Pre-requisites: Eclipse IDE (for Java EE developers), Apache Tomcat

Step 1: Launch Eclipse IDE and create a new Dynamic Web Project called AngularRouting. Choose the target runtime as Apache Tomcat 7.0

Step 2: Create HTML page

Create a new HTML page called index.html and place it inside the WebContent folder of your web project. In order to implement routing, the first thing to do is add the extra JavaScript inside the head section as follows!

index.html

....
  <head>
    <title>AngularJS Routing tutorial </title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
  </head>
....

Next, let’s implement our $routeProvider. The $routeProvider is configured in the module’s config() function via calls to the when() and otherwise() functions.

index.html

....
var app = angular.module("demo",['ngRoute']);
app.config(['$routeProvider',
		  function($routeProvider) {
			$routeProvider.
				when('/ShowResult/:id', {
					templateUrl: 'templates/show_result.html',
					controller: 'ShowResultController'
				}).
				otherwise({
					redirectTo: '/'
				});
		}]);
....

We also need to register the ShowResultController and hence navigate to the new page depending upon the request parameter (in this case id). Here’s how our HTML page finally looks,

index.html

<!DOCTYPE html>
<html ng-app="demo">
  <head>
    <title>AngularJS Routing tutorial </title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
  </head>
  <body>
	
	<div ng-controller="TableController">

	    <h2>Student data</h2>
		
		<table>
		    <tr>
			  <th> Id </th>
			  <th> Name </th>
			  <th> Age </th>
			  <th> Email </th>
			  <th> City </th>
			  <th> Action </th>
			</tr>
		   <tr ng-repeat="student in students">
		      <td>{{ student.id }} </td>
		      <td>{{ student.name | uppercase}} </td>
			  <td>{{ student.age }} </td>
			  <td>{{ student.email | lowercase }} </td>
		      <td>{{ student.city | uppercase}} </td>
			  <td> <a href="#ShowResult/{{student.id}}">Show Result</a></td>
		  </tr>	   
		</table>
	 	
		<div ng-view></div>

		
	</div>

	<script type="text/javascript">
		
		var app = angular.module("demo",['ngRoute']);
		app.controller("TableController", function($scope){
		    $scope.students = [
				{ id:"101", name: 'Hari', city: 'Mumbai', email:'hari@gmail.com',age:'16'},
				{ id:"102", name: 'Alexander', city: 'Paris', email:'alex@gmail.com',age:'18'}
			];
		});
		
		app.config(['$routeProvider',
		  function($routeProvider) {
			$routeProvider.
				when('/ShowResult/:id', {
					templateUrl: 'templates/show_result.html',
					controller: 'ShowResultController'
				}).
				otherwise({
					redirectTo: '/'
				});
		}]);
		
		app.controller('ShowResultController', function($scope, $routeParams) {
		    $scope.id = $routeParams.id;
		    
		    if($scope.id == 101){
		    	$scope.message = 'The result for student is passed';
		    }else{
		    	$scope.message = 'The result for student is failed';
		    }
		});
	
	</script>
	
  </body>
</html>

Important: Notice the ngView directive in the above page. Inside the div with the ngView directive (can also be written ng-view) the HTML template specific to the given route will be displayed.

show_result.html

<h2>Show Result</h2>
 
{{ message }}

Finally, save all changes and make sure no errors are present. Run the application on the Tomcat server and you should see the following output!

output

Reference: Routing in AngularJS

AngularJS: Custom directives

Hello everyone!

Directives play an important role in AngularJS applications allowing developers to interact and hence simplify DOM manipulation. One of the most important features of a web application is reusability. AngularJS helps us to build custom directives that can in turn modify or even create a totally new behavior in HTML. To call a directive from HTML, we can simple apply the directive in the DOM. At present, there are four different types of directives namely,

1. Element directives

An element directive is activated when AngularJS finds a matching HTML element in the HTML template. Angular normalizes an element’s tag and attribute name to determine which elements match which directives.

2. Attribute directives

In HTML, we mention attributes for a particular tag. This tag holds the code snippet. Attribute directives help to write specific code that such tags can simply include.

3. CSS class directives

4. Comment directives

Note: AngularJS recommends that you try to use element and attribute directives, and leave the CSS class and comment directives (unless absolutely necessary).

Through this tutorial, we will learn how to use the element directive in AngularJS.

Pre-requisites: Eclipse IDE (for Java EE developers), Apache Tomcat 7.0

Step 1: Launch Eclipse IDE and create a new Dynamic Web Project called AngularCustomDirectives with module version 3.0. Create the following index.html page in the WebContent folder.

index.html

<!DOCTYPE html>
<html ng-app="demo">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
  </head>
  <body>
	
	<div ng-controller="ListController">
		<customerinfo></customerinfo>
	</div>

	<script type="text/javascript">	
		var app = angular.module("demo",[]);
		app.directive('customerinfo', function() {
			
			var directive = {};
		    directive.restrict = 'E'; /* restrict this directive to elements */
			directive.templateUrl = "html-templates/customerinfo-template.html";
			
			return directive;
			
		});
		
		app.controller("ListController", function($scope){
		    $scope.customers = [
				{ name: 'Hari', city: 'Mumbai', email:'hari@gmail.com',age:'16'},
				{ name: 'Alexander', city: 'Paris', email:'alex@gmail.com',age:'18'}
			];
		});
		
	</script>
	
  </body>
</html>

The restrict field is used to set if the directive should be activated by a matching HTML element, or an element attribute. By setting restrict to E one can specify that only HTML elements named customerinfo should activate the directive.

Step 2: Create a new folder called html-templates under the WebContent folder and create the customerinfo-template.html file as follows.

customerinfo-template.html

	<h2>List of customers</h2>
	<ul>
		<li ng-repeat="customer in customers">
		    Name: {{ customer.name |uppercase}} 
		    Age: {{ customer.age }} 
		    Email: {{ customer.email |lowercase }} 
		    City: {{ customer.city | uppercase}}
		</li>
	</ul>

Save all changes. Make sure no errors are present. Run the project on the Tomcat server to launch the corresponding web page in a browser and you should see the following output!

output

Reference: AngularJS directives

AngularJS: Form validation

Hello everyone!

In my previous post we learnt how to get started with AngularJS. In general, forms and controls provide validation services so that the end user can be notified of invalid input. As mentioned on the developer’s page, the ng-submit directive prevents the default action (which for form means sending the request to the server and reloading the current page). In Angular, one can submit a form either using a button element with an ng-click attribute or by using the ng-submit directive.

Through this post we will learn how to implement form validation in AngularJS.

Pre-requisites: Windows 7, Notepad or any text editor

Launch Notepad or any text editor and create a new HTML page called form_validation.html as follows.

form_validation.html

<!DOCTYPE html>
<html ng-app="demo">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
	
	<style type="text/css">
	    
        .ng-invalid.ng-dirty{
		  border-color: #FA787E;
		}
		
		.ng-valid.ng-dirty{
		  border-color: #78FA89;
		}
	</style>
	
  </head>
  <body>
	
	<div ng-controller="ListController">

	    <h2>List of submissions </h2>  
		<ul>
		   <li ng-repeat="student in students">
		     Name: {{ student.name | uppercase}}
		     Email : {{ student.email | lowercase }}
		     City: {{ student.city | uppercase}}
		  </li>	   
		</ul>
	
		<h2>Please fill the below form</h2>
		
		<form ng-controller="FormController" name="myForm" ng-submit="myForm.$valid && addStudent(student)" novalidate>
		
    	  Name: <input type="text" ng-model="student.name" placeholder="Enter your name" required/> <br>
		  Email: <input type="email" ng-model="student.email" placeholder= "Enter your email addresss" required/> <br>
		  City: <input type="text" ng-model="student.city" placeholder="Enter your city"/> <br>
		  
		 <input type="submit" value="Submit"/>
	
		</form>
		 	
	</div>

	<script type="text/javascript">
		
		var app = angular.module("demo",[]);
		app.controller("ListController", function($scope){
		    $scope.students = [
				{ name: 'Hari', city: 'Mumbai', email:'hari@gmail.com'},
				{ name: 'Alexander', city: 'Paris', email:'alex@gmail.com'}
			];
		});
		
		app.controller("FormController", function($scope){
			$scope.addStudent = function(student){
				$scope.students.push(student);
			};
		});
		
	</script>
	
  </body>
</html>

Open the above page in a web browser. If no errors occur then you should see the following output before and after the form submission!

output_1

output_2

That’s it for this AngularJS tip. Stay tuned for more! 🙂

Getting started with AngularJS!

The web is constantly evolving. Earlier, when a browser sent a request to the web server, the server would respond with the corresponding webpage & assets required to load the page. However, when a user clicked a link on the page, the browser would download the same files again. AngularJS is an open source web application framework designed to overcome such limitations. It is maintained by Google and the community at large.

AngularJS is by far one of the most popular technologies for developing MVC based web applications. It supports rapid front end development including features such as two way data binding, dependency injection, custom directives etc with the goal of improving testability and performance. Through this post, we will learn how to get started with AngularJS.

Pre-requisites: Windows 7, Notepad or any text editor, JavaScript

Modules

Modules are used to define applications. A module acts as a container for the different parts of an app, including directives, controllers, services etc. All application controllers should belong to a module. For example,

<div ng-app="demo">
 {{ Hello, Angular!}}
</div>

A reference has been made to the demo module using the ng-app directive.

Directives

AngularJS directives are basically extended HTML attributes with the prefix ng-. As mentioned on the developer’s page, directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS’s HTML compiler ($compile) to attach a specified behavior to that DOM element or even transform the DOM element and its children.

Controllers

In Angular, a Controller is a JavaScript constructor function that is used to augment the Angular Scope. A Controller is attached to the DOM via the ng-controller directive.

Now, it’s time to implement the above concepts using an example. Let’s create an HTML page called test.html and write the following code.

test.html

<!DOCTYPE html>
<html ng-app="demo">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
  </head>
  <body>
	<div>
      <input type="text" ng-model="userName" placeholder="Enter a name here">
        Hello, {{ userName}}!
    </div>
	
	<h2>List of students</h2>
	<div ng-controller="ListController">
		<ul>
		   <li ng-repeat="student in students">{{ student.studentName | uppercase}}</li>	   
		</ul>
	</div>

	<script type="text/javascript">
		
		var app = angular.module("demo",[]);
		app.controller('ListController', function($scope) {
			$scope.students = [
				{ studentName: 'Hari', city: 'Mumbai'},
				{ studentName: 'Alexander', city: 'Paris'},
				{ studentName: 'Zen', city: 'Tokyo'},
				{ studentName: 'Benjamin', city: 'New York'}
			];
		});   
	</script>
	
  </body>
</html>

The above example demonstrates the use of the ng-app and the ng-controller directive. It also explains data binding using AngularJS. If you open the page in a web browser you should see the following output.

output

In the upcoming tutorials we will learn how to use some more features of Angular JS. Till then happy coding! 🙂

Reference: Angular JS Developer Guide