Listing 3.3 shows how to implement dependency injection with two modules, each with a value provider and a controller. Lines 2 and 8 add the value providers. Lines 3 and 9 use dependency injection to inject the value providers into the controllers for each module.
Notice in line 6 that the definition for the myApp
module includes the myMod
module in its dependency list. This injects myMod
, including the controllerB
functionality, enclosed inside.
Listing 3.4 shows HTML that implements the myApp
module as the AngularJS application. Notice that it uses both the controllerA
and the controllerB
controllers. They can be used because the myMod
module was injected into the myApp
module. Figure 3.2 shows the resulting web page, with a different message from each module’s controller.
01 var myMod = angular.module('myMod', []);
02 myMod.value('modMsg', 'Hello from My Module'),
03 myMod.controller('controllerB', ['$scope', 'modMsg',
04 function($scope, msg) {
05 $scope.message = msg;
06 }]);
07 var myApp = angular.module('myApp', ['myMod']);
08 myApp.value('appMsg', 'Hello from My App'),
09 myApp.controller('controllerA', ['$scope', 'appMsg',
10 function($scope, msg) {
11 $scope.message = msg;
12 }]);
01 <!doctype html>
02 <html ng-app="myApp">
03 <head>
04 <title>AngularJS Dependency Injection</title>
05 </head>
06 <body>
07 <div ng-controller="controllerA">
08 <h2>Application Message:</h2>
09 {{message}}
10 </div><hr>
11 <div ng-controller="controllerB">
12 <h2>Module Message:</h2>
13 {{message}}
14 </div>
15 <script src="http://code.angularjs.org/1.2.9/angular.min.js"></script>
16 <script src="/js/injector_custom.js"></script>
17 </body>
18 </html>