Listing 3.1 shows a very basic example of using dependency injection to inject functionality from the $scope
and $window
service into an AngularJS controller. The AngularJS app defined in Listing 3.1 is very simple. On line 2 it defines a basic controller and uses dependency injection to inject the $scope
and $window
service, and then in lines 3 and 4 it uses the $window
service to display an alert pop-up with a message stored in the $scope
.
Listing 3.2 shows the HTML page that uses the myApp module defined in Listing 3.1 and implements the view for controllerA
. Figure 3.1 shows the resulting web page and alert message.
01 var myMod = angular.module('myApp', []);
02 myMod.controller('controllerA', ['$scope', '$window',
03 function($scope, $window) {
04 $scope.message = "My Module Has Loaded!";
05 $window.alert($scope.message);
06 }]);
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>This Page has an Alert</h2>
09 </div><hr>
10 <script src="http://code.angularjs.org/1.2.9/angular.min.js"></script>
11 <script src="js/inject_builtin.js"></script>
12 </body>
13 </html>