Controllers are pieces of code that are intended to provide business logic by augmenting scope. You create controllers by using the controller()
method on the Model
object of an application. This function registers a controller as a provider in the module, but it does not create an instance of the controller. That occurs when the ng-controller
directive is linked in an AngularJS template.
The controller()
method accepts the controller name as the first parameter and an array of dependencies as the second parameter. For example, the following code defines a controller that uses dependency injection to access a value
provider named start
:
angular.module('myApp', []).
value('start', 200).
controller('Counter', ['$scope', 'start',
function($scope, startingValue) {
}]);
When a new instance of a controller is created in AngularJS, a new child scope specific to that controller is also created and accessible via the $scope
service that is injected into the Counter
controller above. Also in the example above, the start provider is injected into the controller and passed to the controller function as startingValue
.
The controller must initialize the state of a scope that is created and added to it. The controller is also responsible for any business logic attached to that scope. This can mean handling update changes to the scope, manipulating scope values, or emitting events based on the state of the scope.
Listing 22.1 shows how to implement a controller that utilizes dependency injection, initializes some values, and implements rudimentary business logic, using inc()
, dec()
, and calcDiff()
functions.
01 angular.module('myApp', []).
02 value('start', 200).
03 controller('Counter', ['$scope', 'start',
04 function($scope, start) {
05 $scope.start = start;
06 $scope.current = start;
07 $scope.difference = 0;
08 $scope.change = 1;
09 $scope.inc = function() {
10 $scope.current += $scope.change;
11 $scope.calcDiff();
12 };
13 $scope.dec = function() {
14 $scope.current -= $scope.change;
15 $scope.calcDiff();
16 };
17 $scope.calcDiff = function() {
18 $scope.difference = $scope.current - $scope.start;
19 };
20 }]);
18.224.6.211