Angularjs explicit dependency injection

Time:2020-11-10

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:

Angularjs explicit dependency injection

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.

Angularjs explicit dependency injection

Recommended Today

Think about open source project promoting rust search extension: quickly search rust documents in the browser address bar

Open source project name:Rust Search Extension Introduction to open source projects:Quick search for rust documents in the browser address barOpen source project type:teamProject creation time:2020 GitHub data:375 Star,18 ForkGitHub address:https://github.com/huhu/rust-search-extension Rust search extension is a plug-in that can quickly search rust documents, Crites, built-in properties and error codes in the browser address bar. It supports […]