trainingtrains Logo

91-9990449935

 0120-4256464

AngularJS Dependency Injection

AngularJS comes with a built-in dependency injection mechanism. It facilitates you to divide your application into multiple different types of components which can be injected into each other as dependencies.

Dependency Injection is a software design pattern that specifies how components get holds of their dependencies. In this pattern, components are given their dependencies instead of coding them within the component.

Modularizing your application makes it easier to reuse, configure and test the components in your application. Following are the core types of objects and components:

  • value
  • factory
  • service
  • provider
  • constant

These objects and components can be injected into each other using AngularJS Dependency Injection.


Value

In AngularJS, value is a simple object. It can be a number, string or JavaScript object. It is used to pass values in factories, services or controllers during run and config phase.

Here, values are defined using the value() function on the module. The first parameter specifies the name of the value, and the second parameter is the value itself. Factories, services and controllers can now reference these values by their name.

Injecting a value

To inject a value into AngularJS controller function, add a parameter with the same when the value is defined.


Factory

Factory is a function that is used to return value. When a service or controller needs a value injected from the factory, it creates the value on demand. It normally uses a factory function to calculate and return the value.

Let's take an example that defines a factory on a module, and a controller which gets the factory created value injected:

Injecting values into factory

To inject a value into AngularJS controller function, add a parameter with the same when the value is defined.

Note: It is not the factory function that is injected, but the value produced by the factory function.


Service

In AngularJS, service is a JavaScript object which contains a set of functions to perform certain tasks. Services are created by using service() function on a module and then injected into controllers.


Provider

In AngularJS, provider is used internally to create services, factory etc. during config phase (phase during which AngularJS bootstraps itself). It is the most flexible form of factory you can create. Provider is a special factory method with a get() function which is used to return the value/service/factory.


Constants

You cannot inject values into the module.config() function. Instead constants are used to pass values at config phase.

Let's take an example to deploy all above mentioned directives.

Test it Now
Next TopicAngularJS Filters