Understanding AngularJS Dependency Injection

Dependency injection in AngularJS is supremely useful, and the key to making easily testable components. This article explains how Angular’s dependency injection system works.

Dependency Injection is a software design pattern in which dependencies are injected into the components instead of hard coding them. This relieves a component from locating the dependency and makes dependencies configurable. This helps in making components reusable, maintainable and testable.

Following are the core components which can be injected into each other as dependencies.

  1. Value
  2. Factory
  3. Service
  4. Provider
  5. Constant

The easiest way to remember the five components of dependency injection would be by memorizing the following sentence. “A Factory Provides Value by Constant Service“.

Dependency Injection in AngularJS

Value

Value is a simple JavaScript object and it is used to pass values to controller during the config phase.

Factory

A factory is a function which is used to return value. Factories create value on demand whenever a service or controller requires. It normally uses a factory function to calculate and return the value.

Service

A Service is a singleton JavaScript object containing a set of functions to perform certain tasks. Services are defined using service() functions and then injected into controllers.

Provider

If you were to create services or factories or values during the config phase of AngularJS (the phase during which AngularJS bootstraps itself) then you would use Providers. Provider is a special factory method with a method get() which is used to return the value/service/factory.

Constant

Constants are used to pass values at config phase considering the fact that values can not be used during config phase.

Putting them all together:

Try this live at http://plnkr.co/edit/GFsUGMiwZhha9O9tUz3p

Top