Home » AngularJS6 July 2017

AngularJS: Dependency Injection (DI)

This article shows how you can work with Dependency Injection (DI) in AngularJS 1.x application. It’s just about passing dependencies to AngularJS controller. Rest of the work on injecting dependencies is taken care by AngularJS.

Dependency Injection (DI) is basically about passing a dependency object to another dependent object that uses it as a service. A service is provided to the client as a dependency object. So that, the client does not have to create the service by itself.

There are different ways of passing dependency to the AngularJS controller.

Dependency as an anonymous Function

Here is an example controller code from previous article. This fetches JSON data from countries.json file. Dependency to the controller is passed as a direct anonymous function ( function($scope, $http) { } ).

This is a simple approach but has drawback. This breaks the application when we minify the code because service names get renamed when the code is minified.

Dependency as inline Array annotation

This is an alternative to the above approact of passing dependency as anonymous function. We pass dependencies as array arguments. This way of dependency injection will not break the application when the code is minified.

In our $http service example code, we use it as below:

In array arguments, instead of using anonymous function, we can also used named function, i.e. define a different function separately and use that function name in the array argument.

Dependency as $inject Property

$inject property is an array of service names. We inject those services in the array using the $inject property. This way of dependency injection will not break the application when the code is minified.

Here’s the example code using $inject property:

Hope this helps. Thanks.

AngularJS

Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed

Comments are closed.