AngularJS : Controllers :- Tutorial 2

In this tutorial we will be learning about Controllers in Angular.

Controllers are used to bind a view to its business logic. Ideally a view should have a controller. All the initialization stuffs for that particular view also goes into the controller e.g. Greeting an user while he logs in etc.

In brief:
1. Initialize the view using $scope object.
2. Add business logic to a view
For any other purpose apart from these one needs to create angular services.

We will go ahead and look at how to define controllers:
1. Using Scope object :

.controller('ControllerName1', function($scope)
                      {
                          $scope.name = "Aditya";
                      });

2. Plain function :

.controller('ControllerName', function()
                      {
                          var scope = this;
                          scope.name = "Aditya S";
                      });

Now how do we use this in a HTML page. We need to first give our HTML application a ng-app namespace as

<html lang="en" ng-app="Namespace">

Then we can put the above scripts as below :

<head>
<meta charset="utf-8">
<title>Hello World</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js">
 </script>
<script>
 var Namespace = angular.module('Namespace',[]);

 Namespace.controller('ControllerName', function()
 {
 var scope = this;
 scope.name = "Aditya S";
 });

 Namespace.controller('ControllerName1', function($scope)
 {
 $scope.name = "Aditya";
 });
 </script>
</head>

We can go ahead and use them in our body as :

<body >
<div ng-controller="ControllerName as control">Hello {{control.name}}</div>
<div ng-controller="ControllerName1">Hello {{name}}</div>
</body>

From above we are binding both the Controllers in different manner, as the first one is creates a local variable which can be used by “classname.propertyname” and the second uses scope to create and hence can be directly used with “propertyname”.

The entire application looks like :

<!DOCTYPE html>
<html lang="en" ng-app="Namespace">
<head>
<meta charset="utf-8">
<title>Hello World</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js">
 </script>
<script>
 var Namespace = angular.module('Namespace',[]);

 Namespace.controller('ControllerName', function()
 {
 var scope = this;
 scope.name = "Aditya S";
 });

 Namespace.controller('ControllerName1', function($scope)
 {
 $scope.name = "Aditya";
 });
 </script>
</head>

<body >
<div ng-controller="ControllerName as control">Hello {{control.name}}</div>
<div ng-controller="ControllerName1">Hello {{name}}</div>
</body>
</html>
 

Happy Angularing !!

One thought on “AngularJS : Controllers :- Tutorial 2

Leave a comment