AngularJS Controller:

The controller in AngularJS is a JavaScript function that maintains the application data and behavior using $scope object.

You can attach properties and methods to the $scope object inside a controller function, which in turn will add/update the data and attach behaviours to HTML elements. The $scope object is a glue between the controller and HTML.

The ng-controller directive is used to specify a controller in HTML element, which will add behavior or maintain the data in that HTML element and its child elements.

The following example demonstrates attaching properties to the $scope object inside a controller and then displaying property value in HTML.

Example: AngularJS Controller

<!DOCTYPE html>
<html >
<head>
    <title>AngualrJS Controller</title>
    <script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myNgApp">
    <div ng-controller="myController">
        {{message}}
    </div>
    <script>
        var ngApp = angular.module('myNgApp', []);

        ngApp.controller('myController', function ($scope) {
            $scope.message = "Hello World!";        
        });
    </script>
</body>
</html>

Result:

Hello World!

In the above example, ng-controller="myController" directive is applied to the <div> element where "myController" is the name of the controller. Inside div element, we have specified {{message}} expression.

The $ sign is used as prefix in all the built-in objects in AngularJS, so that we can differentiate AngularJS built-in objects and other objects.

Now, to create "myController", we need to create an application module. The module defines an application and keeps its parts like controllers, services etc. out of global scope. (You will learn about the module in the next section.) After creating a module, we add a controller function using the controller() method where the first parameter should be the name of the controller and second parameter should be a function for the controller. The controller function includes $scope parameter which will be injected by AngularJS framework.

Note : AngularJS framework injects $scope object to each controller function. It also injects other services if included as a parameter of controller function.

The following figure illustrates the above example.

Steps to create an AngularJS Controller
Steps to create an AngularJS Controller

Attach Behaviors:

You can attach multiple methods to the scope object inside a controller, which can be used as an event handler or for other purposes.

The following example demonstrates handling click event of a button.

Example: Handle Button Click

<!DOCTYPE html>
<html>
<head>
    <title>AngualrJS Controller</title>
    <script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myNgApp">
    <div ng-controller="myController">
        Enter Message: <input type="text" ng-model="message" /> <br />
        <button ng-click="showMsg(message)">Show Message</button>
    </div>
    <script>
        var ngApp = angular.module('myNgApp', []);

        ngApp.controller('myController', function ($scope) {
            $scope.message = "Hello World!";       
            
            $scope.showMsg = function (msg) {
                alert(msg);
            }; 
        });
    </script>
</body>
</html>

In the above example, we have attached showMsg() function to the scope object. The showMsg() method is called on button click. The ng-click directive is used to handle click event in AngularJS application.

Note that the properties and methods attached to the scope object inside a particular controller is only available to the HTML elements and its child elements where ng-controller directive is applied.

Example: Controller

<!DOCTYPE html>
<html>
<head>
    <title>AngualrJS Controller</title>
    <script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myNgApp">
    <div id="div1" ng-controller="myController">
        Message: {{message}} <br />       
        <div id="div2">
            Message: {{message}}
        </div>
    </div>
    <div id="div3">
        Message: {{message}}
    </div>
    <div id="div4" ng-controller="anotherController">
        Message: {{message}}
    </div>
    <script>
        var ngApp = angular.module('myNgApp', []);

        ngApp.controller('myController', function ($scope) {
            $scope.message = "This is myController";       
        });

        ngApp.controller('anotherController', function ($scope) {
            $scope.message = "This is anotherController";       
        });
    </script>
</body>
</html>

Result:

Message: This is myController 
Message: This is myController 
Message:
Message: This is anotherController

In the above example, the "message" property is defined inside myController, so it will only be available to div1 and div2 but not div3 and div4. The same way, message property defined inside anotherController will only be available to div4. The div3 element does not come under any controller, so "message" property will be null or undefined.

Attach Complex object:

You can also attach an object to the $scope inside controller and display value of its properties in HTML.

Example: Attach an object

<!DOCTYPE html>
<html>
<head>
    <title>AngualrJS Controller</title>
    <script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myNgApp">
    <h2>Student Information:</h2>
    <div ng-controller="myController">
        First Name: {{student.firstName}} <br />
        Last Name: {{student.lastName}}
    </div>
    <script>
         var ngApp = angular.module('myNgApp', []);
        
        ngApp.controller('myController', function ($scope) {
            $scope.student = { firstName: 'James', lastName: 'Bond' };
        });
    </script>
</body>
</html>

Result:

First Name: James 
Last Name: Bond

As you can see in the above example, a student object is attached to the $scope and its properties and methods can be accessed using an expression, ng-model, or ng-bind directives with dot notation.

Nested Controllers:

Angular allows nested controllers. The following example demonstrates multiple controllers.

Example: Nested Controllers

<!DOCTYPE html>
<html>
<head>
    <title>AngualrJS Controller</title>
    <script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myNgApp">
    <div ng-controller="parentController">
        Message: {{message1}} 
        <div ng-controller="childController">
            Parent Message: {{message1}}  </br>
            Child Message: {{message2}}
        </div>
        Child Message: {{message2}}
    </div>
    <script>
         var ngApp = angular.module('myNgApp', []);

        ngApp.controller('parentController', function ($scope) {
            $scope.message1 = "This is parentController";
        });

        ngApp.controller('childController', function ($scope) {
            $scope.message2 = "This is childController";
        });
    </script>
</body>
</html>

Result:

Message: This is parentController 
Parent Message: This is parentController 
Child Message: This is childController
Child Message: 

As you can see in the above example, a child controller can access properties and methods attached in parent controller function, whereas parent controller cannot access properties and methods attached in child controller.

Minification Syntax:

All the script files in AngularJS application should be minified in the production environment.

The minification process shortens parameter and function names. As mentioned before, AngularJS controller function may include $scope or other parameters. If minification process changes the parameter names then AngularJS application will break because Angular framework needs the same parameter name for built-in objects such as $scope. Use the following syntax so that minification will not change the parameter name.

Example: Controller Syntax for minification

<!DOCTYPE html>
<html >
<head>
    <script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myNgApp">
    <div ng-controller="myController">
        {{message}}
    </div>
<script>
    var ngApp = angular.module('myNgApp', []);

    ngApp.controller('myController', ['$scope', function ($scope) {
        $scope.message = "Hello World!";        
    }]);
</script>   
</body>

In the above example, we have given name of the parameter and controller function in the square bracket []. Parameter name will be first and last member will be action controller function in the square brackets. This will tell minifier not to convert $scope name in the minification process.