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. Each controller accepts $scope as a parameter, which refers to the application/module that the controller needs to handle.
<div ng-app = "" ng-controller = "studentController"> ... </div>
Here, we declare a controller named studentController, using the ng-controller directive. We define it as follows −
<script> function studentController($scope) { $scope.student = { firstName: "Mahesh", lastName: "Parashar", fullName: function() { var studentObject; studentObject = $scope.student; return studentObject.firstName + " " + studentObject.lastName; } }; } </script>
Now we can use studentController’s student property using ng-model or using expressions as follows −
Enter first name: <input type = "text" ng-model = "student.firstName"><br> Enter last name: <input type = "text" ng-model = "student.lastName"><br> <br> You are entering: {{student.fullName()}}
The following example shows the use of controller −
<html> <head> <title>Angular JS Controller</title> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app = "mainApp" ng-controller = "studentController"> Enter first name: <input type = "text" ng-model = "student.firstName"><br> <br> Enter last name: <input type = "text" ng-model = "student.lastName"><br> <br> You are entering: {{student.fullName()}} </div> <script> var mainApp = angular.module("mainApp", []); mainApp.controller('studentController', function($scope) { $scope.student = { firstName: "Mahesh", lastName: "Parashar", fullName: function() { var studentObject; studentObject = $scope.student; return studentObject.firstName + " " + studentObject.lastName; } }; }); </script> </body> </html>
Open the file testAngularJS.htm in a web browser and see the result.