In Angular, a Controller is defined by a JavaScript constructor function. We can attach any controller to the view using the
ngController
directive. After using this directive, the view and controller start to share the same scope (
$scope
-It is nothing but an object that Glues the View with Controller. They hold the Model data that we need to pass to view)
snippet
<!doctype html>
<html ng-app="payroll">
<head>
<title>Employee Details</title>
<script src="angular.js"></script>
<script>
var payroll = angular.module("payroll", []);
payroll.controller("payrollController", function($scope) {
$scope.firstName = "David";
$scope.lastName = "Pop";
$scope.designation = "Engineer";
$scope.fullName = function() {
return $scope.firstName + " " + $scope.lastName;
};
});
</script>
</head>
<body ng-controller="payrollController">
</body>
</html>
There is another way to attach a controller to a specific view. We will learn how to create a single-page application using the
$route
service. To avoid undesired duplicated behavior, remember to avoid the
ngController
directive while using the $route service.
Nested controllers
Sometimes, our controller can become too complex, so we can split the behavior into separated controllers. This can be achieved by creating nested controllers, which means registering controllers that will work only inside a specific element of the view, as shown in the following code:
<body ng-controller="employeeCtrl">
<div ng-controller="employeeNestedCtrl">
</div>
</body>
The scope of the nested controllers will inherit all the properties of the outside scope and overrides it in case of equality.