Dependency Injection in Angular JS

AngularJS is a front-end framework used to structure dynamic web applications, but there is a feature which is often overlooked and guarantees communication between components, services, factories and the like. This feature is known as the Angular Injector Subsystem, which is a framework for dependency injection. Today I will be going over what dependency injection generally is, how it can be used in AngularJS, and the importance of understanding it in the first place. Let’s get started.

What is Dependency Injection?

Dependency Injection is a pattern in which a class can receive dependencies externally, rather than internally. In AngularJS, just replace the word “Class” with “Component” and it would mean the same thing.

Dependency Injection also follows a process called the Dependency Inversion Principle, a form used to decouple software modules. Below is a visual depiction of how the DIP works:

Classes no longer need to rely on dependencies, since all dependencies are stored in the interface, and can be pulled using the dependency name in a class’s constructor.

How does Dependency Injection work in AngularJS?

  • Module methods: methods which can specify functions to run at call time. ex: (.run & .config)
  • Controllers: Contain special dependencies such as $ctrl and $scope.
  • Factory methods: Methods registered with modules. ex: (Services, directives, filters, and animations)

Now that we understand some methods, let’s take a look at some examples of how we can use some of these methods in our code:

In the example above, there is a module titled ‘map-displayer’ which holds the service titled ‘google-Maps’. Within this service would be the standard $http GET request. Now take a look at the example below and notice how the component ‘app’ is contained within the same module.

This module helps act as a interface for both the component and the service which uses the integrated AngularISS to store dependencies depending on the name of the component/service. From there all it takes to inject the dependencies from the provided service into the component is to type the service’s name as an argument for the component’s controller. This will automatically tell the module that the dependencies under said name will be injected into the component.

The importance of Dependency Injection in AngularJS.

JS Dev

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store