Understanding AngularJS Controllers

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.    
  6. <div ng-app="myAngularApp" ng-controller="Ctrl">  
  7.    
  8. City: <input type="text" ng-model="city"><br><br><br>  
  9. Country: <input type="text" ng-model="country"><br><br><br>  
  10. Result: {{city + " " + country}}  
  11.    
  12. </div>  
  13.    
  14. <script>  
  15. var app = angular.module('myAngularApp', []);  
  16. app.controller('Ctrl', function($scope) {  
  17.     $scope.city = "Mumbai";  
  18.     $scope.country = "India";  
  19. });  
  20. </script>  
  21.    
  22. </body>  
  23. </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.