Implementing Providers and Dependency Injection

After you have defined a module and appropriate providers, you can add the module as a dependency to other modules, controllers, and various other AngularJS objects. You can set the value of the $inject property of the object that depends on the providers. The $inject property contains an array of provider names that should be injected into it.

For example, the following code defines a basic controller that accepts the $scope and appMsg parameters. Then the $inject property is set to an array that contains $scope, which is the AngularJS scope service that provides access to the scope and a custom appMsg. Both $scope and appMsg are injected into the myController function:

var myController = function($scope, appMsg) {
  $scope.message = appMsg;
};
controller['$inject'] = ['$scope', 'appMsg'];
myApp.myController('controllerA', controller);

This method can become a bit clumsy when you’re implementing certain objects, so AngularJS also provides a bit more elegant method for injecting the dependencies, using the following syntax in place of the normal constructor function:

[providerA, providerB, . . ., function(objectA, objectB, . . .) {} ]

For example, the preceding code can also be written this way:

myApp.controller('controllerA', ['$scope', 'appMsg', function($scope, appMsg) {
  $scope.message = appMsg;
}]);

It is critical that you understand dependency injection before continuing, so let’s take a look at a couple of examples. The following sections provide sample listings that implement dependency injection in AngularJS applications.

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

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