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.

When it comes to learning about dependency injection in AngularJS, I found it to be easier learning the general definition, since there are so many variants of dependency injections out there.

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.

Bouncing back to the introduction paragraph, the AngularISS plays a key role in the framework of AngularJS. It’s useful to understand the methods that the AngularISS can provide in your code. Here is a brief list of some methods:

  • 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.

AngularJS’s framework is designed to have dependency injection a priority in keeping code re-usable and prevent the whole application from faltering when one dependency is broken. That is why there are modules used to prevent this very issue built into the framework, so you don’t have to.

JS Dev