AngularJS applications mainly rely on controllers to control the flow of data within the application. Controllers are defined using the ng-controller directive. A controller is a function that contains properties/properties and JavaScript objects. Each controller accepts the $scope parameter to specify the application/module that is controlled by the controller.
<div ng-app="" ng-controller="studentController"> ... </div>
Here, we have declared the controller studentController using the ng-controller directive. As next step, we will define studentController as follows
<script> function studentController($scope) { $scope.student = { firstName: "yiibai", lastName: "com", fullName: function() { var studentObject; studentObject = $scope.student; return studentObject.firstName + " " + studentObject.lastName; } }; } </script>
Now you can use the studentController attribute 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()}}
Example
The following example will demonstrate the use of a controller.
The content of the testAngularJS.html file is as follows:
<html> <head> <title>Angular JS Controller</title> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app="" 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> function studentController($scope) { $scope.student = { firstName: "Mahesh", lastName: "Parashar", fullName: function() { var studentObject; studentObject = $scope.student; return studentObject.firstName + " " + studentObject.lastName; } }; } </script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> </body> </html>
Output
Open textAngularJS.html in a web browser and see the following results: