When you start learning the very first characteristics of AngularJS, you may come across something called Dependency Injection (DI): the premise that AngularJS injects dependencies whenever an application needs them. As a developer, our task is only to pass the dependency to the module and everything else will be taken care by AngularJS.

To create a controller, we pass $scope object and other dependencies to the module’s controller function. For example, to create a ProductController, we are passing $scope object and Calculator service dependencies. As a developer our job is to pass the dependencies and AngularJS will inject them whenever the application needs them.

As a developer, we really don’t care about how AngularJS injects dependencies – we don’t need to know how the injection process works to develop applications.  However, it is better if we know different ways of passing dependencies. In AngularJS, dependencies can be passed in three possible ways. They are as follows:

  • Passing a dependency as Function Arguments
  • Passing a dependency as Array Arguments
  • Passing a dependency using the $inject service

Let us explore these options one by one.

Passing a dependency as a Function Argument

Perhaps most of the time you pass a dependency as a function argument, which is perfectly fine. For example, we pass a $scope object to create a controller as shown in the listing below:

Read full article on the Infragistics blog

Advertisements

One thought on “Different ways of injecting dependency in an AngularJS Application

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s