ngController directive

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)
<!doctype html>
<html ng-app="payroll">
<title>Employee Details</title>
<script src="angular.js"></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;
<body ng-controller="payrollController">

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">

The scope of the nested controllers will inherit all the properties of the outside scope and overrides it in case of equality.
Related Tutorial
Follow Us #
Contents +