Article Series
- Tutorial 1: Angular JS
- Tutorial 2: Controllers
- Tutorial 3: Controllers
- Tutorial 4: Controllers : Advanced
- Tutorial 5: Models
- Tutorial 6: Services
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 stuff for that particular view also goes into the controller, e.g., Greeting a user while he logs in, etc.
In brief:
- Initialize the view using
$scope
object. - 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:
- Using
Scope
object:
.controller('ControllerName1', function($scope)
{
$scope.name = "Aditya";
});
- Plain function:
.controller('ControllerName', function()
{
var scope = this;
scope.name = "Aditya S";
});
Now how do we use this in an HTML page. We need to first give our HTML application an 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 the above, we are binding both the Controllers in a different manner, as the first one 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!!