Angularjs explicit dependency injection
Dependency injection is the signature function of angular. All components, modules, instructions and controllers can be instantiated by using angular’s $injector injector. This is also one of the core functions of angular. It is also part of understanding the internal mechanism of angular.
Generally speaking, angularjs does not need to explicitly inject dependency, because angualrjs will help you implicitly inject. You can ignore what happens inside, but your components, modules, instructions, controllers are bound to the element nodes that declare ng.
However, in order to understand the internal mechanism of angular, we still need to learn how to use angular’s $injector for manual explicit injection. In addition, the explicit injection of angular can define the dependency relationship used when a function is called. In this way, angular can still perform dependency injection when the source code is compressed and the parameter name is changed. But implicit injection does not have this effect.
Now let’s take a look at the code injected explicitly by angularjs.
var aControllerFactory =
function aController($scope, greeter) {
console.log("LOADED controller", greeter);
};
aControllerFactory.$inject = ['$scope', 'greeter'];
var greeterService = function() {
console.log("greeter service");
return {
doTheThing: function methodThatDoesAThing() {}
}//Factory returns the object
};
angular.module ('myapp ', []) // myapp here links to HTML elements
.controller('MyController', aControllerFactory)
.factory('greeter', greeterService);
var injector = angular.injector(['ng', 'myApp']),
controller = injector.get('$controller'),
rootScope = injector.get('$rootScope'),
newScope = rootScope.$new();
controller('MyController', { $scope: newScope });
The result of this code is:
The order of the displayed dependency injection parameters is very important. If the order of the $inject array is different from the order of the injection, the injected elements will be empty.