AngularJS > Components

Controllers in AngularJS

What is controller in AngularJS?


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 

  1. setup the initial state of the $scope object of that controller, in terms of setting up properties, objects, variables value etc. 
  2. attach behavior, specify function etc.
Controller is not used to 
  1. Format data
  2. Filter data
  3. Sharing between controllers
  4. Manipulating DOM

Defining a controller

A controller is defined with the help of controller function that is exposed on a Angular module. It accepts two parameters

  1. 1st parameter - is the name of the controller 
  2. 2nd parameter - is the actual controller definition of what and how it does
    var myApp = angular.module('myApp', []);
    myApp.controller('MyController', function($scope) {
// write controller our code here
    });
In above code snippet, we have decared a controller named "MyController" that calls its function in which $scope object is injected.

Defining a controller (recommended)

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.

Full funcitonal module and a controller

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>
In the above code snippet, we have referenced the AngularJS library. We have created a Module for the page application where the application name is "myApp". Then created a controller named "MyController" and attached a function that has $scope injectable object.

Next, we are setting two properties of $scope object (FirstName and LastName).

After that we have created a behavior (function) named FullDetails that returns a string with the value of FirstName and LastName.

Notice the ng-app attribute of the <body> tag that has been used to attach the module. After that div has ng-controller that has set the controller created with this module "MyController". Inside that we have used Expressions to write the value of FirstName, LastName property of the $scope object and then called the FullDetails() function declared in that controller scope.

To know more about controllers and their How to's, click here.
 Views: 15205 | Post Order: 9




Write for us






Hosting Recommendations