Tutorial: AngularJS Fundamentals


Posted on May 4th, 2014


In this tutorial i will explain AngularJS Fundamentals with a user management demo application.

I have been very happy with jQuery and didnt pay much attention to AngularJS, thinking it is similar to jQuery. But i was so dead wrong.  After reading and exploring this Framework, i fell in love with it instantly.  Without a doubt,  

AngularJS is quickly becoming the dominant JavaScript framework for professional web development.

 

What is AngularJS ?

In short its a javascript framework and follows the concept of MVC. It is used to create Single Page Applications , shortly known as SPA. It makes development and testing really a cake walk.

How does it help ?

Lets say, we need to create a complete Ajax based application. So, what all would you account for ? I suppose the below points would be valid.

  1. Make sure the urls change and can be parsed by bots for better SEO.
  2. Your app might depend on other libraries or classes which you might want to inject only when its required.
  3. You will want the UI to react (like update/insert) whenever you make some changes.
  4. The navigation should be smooth and robust and other views should be able to switch in and out easily.
  5. You will want to make your code more maintainable and scalable.

AngularJS is the solution for all the above mentioned points. It takes care of everything. 

How do i use ?

AngularJS has got a very comprehensive documentation here.  In this post, i will help you to get started.

I will create a user management application to insert, edit and delete users.

Demo - http://playground.ajaxtown.com/angular-um-demo

 

index.html

<!DOCTYPE html>
<html>
<head>
	<title>User Management</title>
	
	<script src="js/angular.min.js"></script>
	<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>	
	<script src="js/app.js"></script>	
	<script src="js/controllers.js"></script>
	<script src="js/services.js"></script>
	
</head>
<body>
	<div ng-app="APP" ng-controller="UserController">

		<h1>			
			User Management <a href="#add" class="btn btn-info btn-xs">Add User</a>
		</h1>
		<div ng-view></div>

	</div>	
</body>
</html>

Here we have included the required js files.

In line 16, ng-app=”APP” defines the scope of your application. You can place it in the <html> tag as well. It is used to auto bootstrap the angularjs application.

ng-controller attaches a controller class to the view. Which means all our business logic can be written inside UserController.

ng-view : All your views will be positioned inside this div. Based on the url, the view gets pushed in and out.

partials/users.html

<div class="row">
  <div class="col-lg-2">
    <input type="text" class="form-control" placeholder="Search" ng-model="q">
  </div> 
</div>
<br/>
<table class="table table-striped table-bordered table-condensed">
	<thead>
		<th>#</th>
		<th>First Name</th>
		<th>Last Name</th>
		<th>Email</th>
		<th>Edit</th>
	</thead>

	<tbody>
		<tr ng-repeat="user in users | filter:q">
			<td>{{$index + 1}}</td>
			<td>{{user.fname}}</td>
			<td>{{user.lname}}</td>
			<td>{{user.email}}</td>
			<td><a href="#edit/{{$index}}">Edit</a> | <a href="#" ng-click="deleteUser($index)">Delete</a></td>
		</tr>
	</tbody>
</table>

The first thing you’ll notice in this template is the use of expressions (“{{“ and “}}”) to return variable values. In AngularJS, expressions allow you to execute some computation in order to return a desired value.

ng-repeat directive is one of the most commonly used and serves to define your template scope when looping through collections. In the example above, it replicates a line in the table for each user in users.

 partials/addUser.html

<div class="row">
  <div class="col-lg-2">
    <input class="form-control" type="text" ng-model="user.fname" placeholder="First Name">
  </div>
  <div class="col-lg-2">
    <input class="form-control" type="text" ng-model="user.lname" placeholder="Last Name">
  </div>
  <div class="col-lg-2">
    <input class="form-control" type="text" ng-model="user.email" placeholder="Email">
  </div>
</div>
<br/>
<div class="row"> 
	<div class="col-lg-2">
		<a class="btn btn-info btn-sm" href="#">Back</a>
		<a ng-click="saveUser()" class="btn btn-danger btn-sm">Save</a>
	</div>
</div>

We are now making use of the ng-model directive; this directive will bind your text field to the $scope.user.fname variable and make sure that its value is always up-to-date with the input value. 

So, when we want to edit a user or add a user, ng-model will be responsible to get the data for editing a user and also to update the data.

ng-click allows us to specify a custom behavior when an element is clicked. So, on clicking this link, saveUser() gets triggered.

 js/services.js

angular.module('APP.services',[]).
		factory('UserService', function($http,$q){

			return {
				getUsers : function () {
					var deferred = $q.defer();

					$http.get('users.json', { data: {} }).success(function(data) {

						deferred.resolve(data);
					});

					return deferred.promise;
				}
			}

})

First we need to fetch the data from the server. To facilitate communication with HTTP servers, AngularJS provides the $http and $q service.  When we make an asynchronous ajax call, we need to wait for the response which is then used in the view.  So it is important to wait for the response before we push in the view. $q promises to do that.

js/controllers.js

angular.module('APP.controllers',[]).
		controller('UserController', function($scope,UserService,$routeParams){
			if (!$scope.users)
			{
				UserService.getUsers().then(function(data){
					$scope.users = data;
				})            
			}

			$scope.deleteUser = function($index) {
				$scope.users.splice($index,1);	
			}
		}).
		controller('AddUserController', function($scope,$location){
						

				$scope.user = {fname:"",lname:""}
				$scope.saveUser = function() {					
					$scope.users.push($scope.user)
					$location.path("/")
				}

		}).
		controller('EditUserController', function($scope,$location,$routeParams){
				
				$scope.user = $scope.users[$routeParams.id]
				$scope.saveUser = function() {					
					$scope.users[$routeParams.id] = $scope.user
					$location.path("/")
				}

		})

Now its time to hook our controller. The UserController is passed with  parameters – $scope,  UserService and $routeParams.

The $scope variable is supposed to link your controller and views. In particular, it holds all the data that will be used within your template.

We pass UserService to receive the data from the ajax call. We create this in services.js

$routeParams allows you to receive the current set of URL parameters.

js/app.js

angular.module("APP",['ngRoute','APP.controllers','APP.services']).
	config(function($routeProvider){

		$routeProvider.
		when('/', {
			templateUrl: 'partials/users.html',
			controller : 'UserController'
		}).
		when('/add', {
			templateUrl: 'partials/addUser.html',
			controller : 'AddUserController'
		}).
		when('/edit/:id', {
			templateUrl: 'partials/addUser.html',
			controller : 'EditUserController'
		}).
		otherwise({
			redirectTo: "/"
		});

	})

app.js hooks up everything together. We pass our controllers and services in this.

ngRoute is a dependency lib to get information about the url parameters.  This is required by $routeProvider to work.

The $routeProvider is responsible to get the appropriate view inside the ng-view directive, defined in index.html

If the url is something like http://localhost/angulardemo/#/add, then it will push theaddUser.html view and link it with the controller AddUserController.

You can download the source code here.

Conclusion:

It is little difficult to explain each and every line but with little bit of javascript knowledge, few of the stuff can be figured out. In the demo, i have used twitter bootstrap to make the UI look nice.

Finally, remember that AngularJS is really powerful in what it does and we have barely touched the surface of it.

If you have any queries in following up with this post, comment !

 


Dependency Injection in PHPFacebook Type Link Preview

Comments
100% Complete