Objectives and outcomes

In this tutorial we are going to learn about AngularJS Controllers. Controllers are the function which controls the application work-flow and also handles the application data. Controllers are declared by using ng-controller directive. Controller is defined between the scripts tags or we can also define them in seperate javascript files.



Below is the example of the controller which calculates the interest

Javascript

<script>
var intr = angular.module("Interest",[]);
intr.controller("Intrcontrol",function($scope)
{
$scope.principal = 100;
$scope.rate = 10;
$scope.time = 1;
$scope.interest = function(){
return ($scope.principal*$scope.rate*$scope.time)/100;
};
});
</script>


HTML

<html>
<head>
<meta charset="utf-8">
<script src="angular-1.4.6/angular.min.js">
</script>
</head>
<body>
<div ng-app="Interest" ng-controller="Intrcontrol">
<form>
<div style="padding:8px;">
Principal:<input type="number" ng-model="principal" required><br/>
Rate:<input type="number" ng-model="rate" required><br/>
Time:<input type="number" ng-model="time" required><br/>
</div>
<p><b>Interest:{{interest()}}</b></p>
</form>
</div>
</body>
</html>


Principal:
Rate:
Time:

Interest:{{interest()}}



In the above example we have declared an app with the name of Interest with controller Intrcontrol. By the use of ng-model we have bind principal, rate and time with the application.
Now the controller refers to application data by using $scope parameter. We have stored the application module in variable intr. However we can also use the same statement like shown below:



angular.module("Interest",[])
.controller("Intrcontrol",function($scope){
});