Dependency injection in AngularJS

  • Dependency Injection is a software design pattern in which an object is given its dependencies, rather than the object creating them itself. Design pattern allows us to remove the hard-coded dependencies and making it possible to change them whenever needed.

Why do you need to inject dependencies ?

  • Separate the process of creation and consumption of dependencies.
  • Let the consumer worry only about how to use the dependency, and leave the process of creation of the dependency to somebody else.
  • Allow concurrent/independent development of the dependency and the dependent entity, while only maintaining a known contract.
  • Facilitate changing of the dependencies when needed.
  • Allow injecting mock objects as dependencies for testing, by maintaining the agreed contract.
There are only three ways a component (object or function) can get a hold of its dependencies:
    • The component can create the dependency, typically using the new operator.
    • The component can look up the dependency, by referring to a global variable.
    • The component can have the dependency passed to it where it is needed.
  • The first two options of creating or looking up dependencies are not optimal because they hard code the dependency to the component. This makes it difficult, if not impossible, to modify the dependencies. This is especially problematic in tests, where it is often desirable to provide mock dependencies for test isolation.
  • The third option is the most viable, since it removes the responsibility of locating the dependency from the component. The dependency is simply handed to the component.

Example 1

function SomeClass(greeter) 
{
this.greeter = greeter;
}
SomeClass.prototype.doSomething = function(name)
{
this.greeter.greet(name);
}

This is desirable, but it puts the responsibility of getting hold of the dependency on the code that constructs Some Class.

 dependency-injection

To manage the responsibility of dependency creation, each AngularJS application has an injector. The injector is a service locator that is responsible for construction and lookup of dependencies.

Using the injector service:

Syntax :

// Provide the wiring information in a module
var myModule = angular.module('myModule', []);

Explain the injector how to build a greeter service. Notice that greeter is dependent on the $window service. The greeter service is an object that contains a greet method.

Example 2

myModule.factory('greeter', function($window) 
{
return
{
greet: function(text)
{
$window.alert(text);
}
};
};

Categorized in: