I am a newbie in Angular.js and came across a topic called "Dependency Injection". I am totally confused after reading the article.
As per the docs, Dependency Injection (DI) is, in angular, method of organizing how components, modules and variables are loaded to various parts of your angular app.
Here's an example of a dependency injection for a controller:
//the controller definition
var Ctrl = function($scope, $http, $location)
{
//now you can use any of the injected variables
//to change the URL after something has happened then you can use $location
$location.path('/path/to/new/page');
}
//and now the injection of the variables
Ctrl.$inject = ['$scope','$http','$location'];
I guess "Ctrl.$inject = ['$scope','$http','$location'];
" this is where Dependency Injection comes into picture.
But I need to understand, what it does and how it is useful?
Thanks.
I want to share of what I thought was a really great example of DI. I'm taking this example from the Angular.js documentation.
This code defines a separate module for directive, filter and service. As written in the documentation:
So, the xmpl module has 3 dependencies which are injected using DI.
Dependency injection allows you to do several things, first it allows for you to specify only what you need in your
controller
,factory
,service
, etc.You have a lot of pre-baked options but injection also allows you to incorporate 3rd party Angular modules into your project.
For example, let's say you want to use animations and routing, but you want to use ui-router instead of
ngRoute
than you would inject them into your app instantiation.Now let's say you have your first controller setup.
But let's say you have a service that you want to use in that controller that handles all of your ajax calls using promises.
First the service would be setup with injecting
$http
to make the server request and$q
for the promises.Now that we have the service setup, we would inject that into our controller so we can easily use it to get the users or do anything else we declared in there:
Edit
$inject
is part of$injector
which you can find more information here.$injector
gets instances of everything that has been injected and$inject
just allows you to setup the injection parameters.$injector
runs behind the scenes.Here is a snippet from the angular source on github - Line 1238