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.
- <!DOCTYPE html>
- <html>
- <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
- <body>
-
- <div ng-app="myAngularApp" ng-controller="Ctrl">
-
- City: <input type="text" ng-model="city"><br><br><br>
- Country: <input type="text" ng-model="country"><br><br><br>
- Result: {{city + " " + country}}
-
- </div>
-
- <script>
- var app = angular.module('myAngularApp', []);
- app.controller('Ctrl', function($scope) {
- $scope.city = "Mumbai";
- $scope.country = "India";
- });
- </script>
-
- </body>
- </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.
This is how we use controllers in AngularJs.