AngularJS applications are controlled by controllers. AngularJS controllers control the data of AngularJS applications.

AngularJS controllers are regular JavaScript Objects that contain attributes/properties, and functions.

A controller is defined using the ng-controller directive. The controller is a JavaScript Object, created by a standard JavaScript object constructor.

Here, we declare a controller named myCtrl, using the ng-controller directive.

<div ng-app = "" ng-controller = "myCtrl">

</div>

 

Example

Open the Example1.html file and add the code in it.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"></script>
    <title></title>
</head>
<body>
    <div ng-app="myApp" ng-controller="myCtrl">
        Name: <input type="text" ng-model="firstName"><br> <br>
        Name: {{firstName}}
    </div>
    <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope) {
            $scope.firstName = "The CodeHubs";
        });
    </script>
</body>
</html>

Application explained:

  • The ng-app=”myApp” directive tells that the <div> element is the “owner” of an AngularJS application.
  • The ng-controller=”myCtrl” is defined as a JavaScript object with $scope as an argument.
  • The $scope refers to application which uses the myCtrl object.
  • The $scope.firstName is a property of myCtrl object. We pass the default value to that.
  • The ng-model=”firstName” directives bind the input field to the controller properties.

 

Controllers In External Files

It is common to store controllers in external files, in larger applications.

Just copy the code between the <script> tags into an external file named nameController.js:

var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope) {
            $scope.firstName = "The CodeHubs";
        });

Open the Example1.html file and add the code in it.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"></script>
    <title></title>
</head>
<body>
    <div ng-app="myApp" ng-controller="myCtrl">
        Name: <input type="text" ng-model="firstName"><br> <br>
        Name: {{firstName}}
    </div>
    <script src="nameController.js"></script>
</body>
</html>

Output: