But first let us understand what a controller is.

A Controller

An AngularJS controller controls the data in AngularJS. These are normal javascript objects used to control the data. A controller is a javascript object created by javascript object constructor.

Let us understand more about a controller by creating a program.

  1. <!DOCTYPE html>
  2. <html>
  3. <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
  4. <body>
  5. <div ng-app="myAngularApp" ng-controller="Ctrl">
  6. City: <input type="text" ng-model="city"><br><br><br>
  7. Country: <input type="text" ng-model="country"><br><br><br>
  8. Result: {{city + " " + country}}
  9. </div>
  10. <script>
  11. var app = angular.module('myAngularApp', []);
  12. app.controller('Ctrl', function($scope) {
  13. $scope.city = "Mumbai";
  14. $scope.country = "India";
  15. });
  16. </script>
  17. </body>
  18. </html>
In the preceding code we have two input textboxes. We have a javascript function in which we have created a controller. AngularJS will invoke the controller with a $scope object. We have to define the controller name in the tag as ng-controller followed by the controller name.

Let us see the output of the code.

output
This is how we use controllers in AngularJs.