Injecting a Built-in Provider into a Controller

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.

Image

Figure 3.1 Implementing dependency injection of the $window service to display an alert message from the $scope.

Listing 3.1 inject_builtin.js: Implementing Dependency Injection of Built-in Services in a Controller


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 }]);


Listing 3.2 inject_builtin.html: Using HTML Code to Implement an AngularJS Module That Implements Dependency Injection


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>


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset