In Angular a controller is a JavaScript function which is used to control the data of AngularJS applications. The job of controller is to build a model for the view to display.
<div ng-app="myApp" ng-controller="myCtrl"> Your Name is: {{ firstName + " " + lastName }} </div> <script> var app = angular.module("myApp", []); app.controller("myCtrl", function($scope) { $scope.firstName = "Mark"; $scope.lastName = "Zuckerberg"; }); </script>
Note: When you make a controller in AngularJS, you have to pass the $scope object as an argument.
It is common in AngularJS applications to put the module and the controllers in separate JavaScript files. In the example below, "myApp.js" contains an application module definition, while "myCtrl.js" contains the controller:
AngularJS.html File
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> </head> <body> <div ng-app="myApp" ng-controller="myCtrl"> {{ firstName + " " + lastName }} </div> <script src="../AngularJS/myApp.js"></script> <script src="../AngularJS/myCtrl.js"></script> </body> </html>
myApp.js
var app = angular.module("myApp", []);
myCtrl.js
app.controller("myCtrl", function($scope) { $scope.firstName = "Mark"; $scope.lastName= "Zuckerberg"; });
In the above example, A controller object is used with two properties (variables) firstName and lastName. A controller can also have methods (functions)
<div ng-app="myApp" ng-controller="myCtrl"> Your Name is (without function): {{ firstName + " " + lastName }} <br> Your Name is (using function): {{ fun() }} </div> <script> var app = angular.module("myApp", []); app.controller("myCtrl", function($scope) { $scope.firstName = "Mark"; $scope.lastName = "Zuckerberg"; $scope.fun = function(){ return $scope.firstName + $scope.lastName; } }); </script>