Angular makes use of dependency injection everywhere. Dependency injection is when a function does not initialize the dependencies it needs. Instead, they are injected into the function as parameters. For example, when a module needs a route provider, it asks for one. The module does not care how or when the route provider was created; it just wants a reference.
You actually use the injector in everything you do in Angular. Angular just does it for you. We will look at $injector
and understand how it works but, most likely, you will not need to use these functions.
We will quickly cover the common ways that objects are injected into functions in Angular. Using a controller as an example, we will cover the two most common methods. Both of these are using Angular's injection behind the scenes:
$scope
and a service:firstModule.controller('DIController', function ($scope, customService) { //$scope and customService are available here console.log($scope); console.log(customService); });
firstModule.controller('DIController', ['$scope', 'customService', function (newScope, custom) { // newScope and custom are available here console.log(newScope); console.log(custom); }]);
Use this to get an Angular injector that you can invoke:
angular.injector(modules)
You can create this object to use Angular's injector object. List out the references you want and then invoke your function.
Here is an example that gets a reference to the $http
service:
var injector = angular.injector(['ng']); var injectTest = function ($http) { console.log($http); }; injector.invoke(injectTest);
You will very rarely ever need to create an injector in Angular. It will be provided for you. You can get a reference to the injector by injecting it or retrieving it from a current module. Here are examples for both:
var injector = angular.element(document.body).injector();
config
:firstModule.config(function ($routeProvider, $injector) { console.log($injector); });
Angular will do this automatically for you, but it is always good to have an idea of what is happening. This is especially true with something that works just like $injector
. Each time a function executes with dependencies, Angular will invoke the function from the injector, sending the correct parameters if they have been created and registered.
18.221.126.56