Controller is a simple JavaScript function that is used to control the data of AngularJS application and increase the AngularJS scope. A controller is attached to the DOM object using ng-controller
directive. When the controller is attached to the DOM, Angular instantiates the controller function and makes available an injectable parameter to the function called $scope
.
Controller is used to
A controller is defined with the help of controller function that is exposed on a Angular module. It accepts two parameters
var myApp = angular.module('myApp', []);
myApp.controller('MyController', function($scope) {
// write controller our code here
});
Above way of defining a controller is perfect and valid however we may end up getting error or malfunction when we minify our code using third party services. Minification replace the long variable name short that may conflict with other variables names. So the safest way to define a controller is using safe-style dependency injection like this.
var app = angular.module('app', []);
app.controller('myController', ['$scope', '$http', function($scope, $http) {
$scope.Square = function(val) {
return 2 * 2;
};
}]);
Notice the highlighted code above where all the depdendency injection parameters are explicitly written as a string separated by comma and the last one is the actual function with the name of the paramters. All three are under an array wrapped with "[" and "]". In this way, the minification services do not touch them and do not change the variables names.
Even if throughout this tutorials, we have not used this approach to define a controller, readers are recommended to use this approach only to define a controller.
Here is a example of this type of controller in action.
In below code snippet, we will see how to combine the definition of a module and controller and create a simple application page.
<!DOCTYPE html> <html> <head> <title>Demo</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> </head> <script> var myApp = angular.module('myApp', []); myApp.controller('MyController', function($scope) { $scope.FirstName = 'Tech'; $scope.LastName = 'Funda'; $scope.FullDetails = function () { return $scope.FirstName + ' ' + $scope.LastName; }; }); </script> <body ng-app="myApp"> <div ng-controller="MyController"> Full name is {{ FullDetails() }} </div> </body> </html>