Differentiation of AngularJS Controllers

If you are interested to learn about the Data Binding

AngularJS controllers control the data of AngularJS applications. AngularJS controllers are regular JavaScript Objects.

AngularJS Controllers

AngularJS applications are controlled by controllers. The ng-controller directive defines the application controller. A controller is a JavaScript Object, created by a standard JavaScript object constructor. 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.

AngularJS Example

div ng-app="myApp" ng-controller="myCtrl"> First Name:
input type="text" ng-model="firstName">
Last Name: <input type="text" ng-model="lastName">
Full Name: 
{{firstName + " " + lastName}}
script><br>var app = angular.module('myApp', []);<br>app.controller('myCtrl', function($scope) 
  $scope.firstName = "John";
<br>  $scope.lastName = "Doe";<br>});

Application explained:

The AngularJS application is defined by  ng-app=”myApp”. The application runs inside the <div>. The ng-controller=”myCtrl” attribute is an AngularJS directive. It defines a controller. The myCtrl function is a JavaScript function. AngularJS will invoke the controller with a $scope object. In AngularJS, $scope is the application object (the owner of application variables and functions). The controller creates two properties (variables) in the scope (firstName and lastName). The ng-model directives bind the input fields to the controller properties (firstName and lastName).

Why are controllers used in AngularJS?

AngularJS application mainly relies on controllers to control the flow of data in the application. A controller is defined using ng-controller directive. A controller is a JavaScript object that contains attributes/properties, and functions.

What is the use of Angular controllers in application?

AngularJS controllers are used to control the flow of data of AngularJS application. A controller is defined using ng-controller directive. A controller is a JavaScript object containing attributes/properties and functions.

Steps to create an AngularJS Controller

Controller Methods

The example above demonstrated a controller object with two properties: lastName and firstName. A controller can also have methods (variables as functions):

AngularJS Example

div ng-app="myApp" ng-controller="personCtrl"> irst Name:i
input type="text" ng-model="firstName">&lt;br><br>Last Name: 
input type="text" ng-model="lastName">
br>Full Name: {{fullName()}} 
/div> script><br>var app = angular.module('myApp', []);
<br>app.controller('personCtrl', 
function($scope) {<br>  $scope.firstName = "John";
<br>  $scope.lastName = "Doe";
<br>  $scope.fullName = function() {<br>    return $scope.
firstName + " " + $scope.lastName;;

Controllers In External Files

In larger applications, it is common to store controllers in external files. Just copy the code between the <script> tags into an external file named personController.js:

AngularJS Example

div ng-app="myApp" ng-controller="personCtrl"> First Name: 
input type="text" ng-model="firstName">&lt;br><br>Last Name: 
input type="text" ng-model="lastName">
br><br>Full Name: {{fullName()}} script src="personController.js">

Another Example

For the next example we will create a new controller file

angular. module('myApp', []). controller('namesCtrl', function($scope) {<br>  $scope.names = [<br>    {name:'Jani',country:'Norway'},
<br>    {name:'Hege',country:'Sweden'},<br>    {name:'Kai',country:'Denmark'}<br>  ]; Save the file as namesController.js:

And then use the controller file in an application:

AngularJS Example

div ng-app="myApp" ng-controller="namesCtrl"> 
ul><br> li ng-repeat="x in names"><br>    {{ x.name + ', ' + x.country }
/li> /ul> /div>;script src="namesController.js">/script>

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>

Differentiation of AngularJS Controllers
Show Buttons
Hide Buttons