Tathagata palm – play with the dependency injection of angualrjs

Time:2021-10-24

Learn about dependencies first

First, we need to understand what isrely on; For example, if you play Lulu and Lulu, and you see others playing little Timo, you think it’s fun and want to play the hero, then you have to go to the store to buy the hero, and then you can use the hero. Owning the hero is your dependence; In short,rely onIs a necessary condition for you to achieve a goal.

Dependency injection is a software design pattern that allows you to remove hard coding between software components and instead create low coupling components through dependency injection, whether in the compilation stage or in the running stage.

Angularjs has an internal dependency injection mechanism. With angularjs, you can divide your app into many reusable components. When these components are needed, you can inject these components into your app through dependency injection.

Gain control of dependencies

There are usually three ways for an object to gain control over its dependencies

  1. Create dependencies internally: the disadvantage of this method is that it is not convenient for future maintenance, making isolation extremely difficult.

  2. Reference through global variables: the disadvantage of this method is that it pollutes the global scope. When the code size reaches a certain degree, it is easy to have problems.

  3. Pass parameters where needed: this method is not only useful for testing, but also does not pollute global variables. It is a good design pattern.AngularJSThis is the method used.

Angularjs dependency injection method

1. Make inferential injection declaration through the parameters of the function

If there is no clear statement,AngularJSIt is assumed that the parameter name is the dependent name. Therefore, it calls the function object internallytoString()Method, analyze and extract the parameter list of the function, and then$injectorInject these parameters into the object instance.

Here is a code example:

HTML code:

html<div ng-app>
    <div ng-controller="MyController">
        <p ng-cloak>{{clock.time | date: "yyyy-MM-dd hh:mm:ss"}}</p>
    </div>
</div>

JS code:

javascriptfunction MyController($scope, $timeout) {
    var updateTime = function () {
        $scope.clock = {
            time: new Date()
        };
        $timeout(function () {
            $scope.clock.time = new Date();
            updateTime();
        }, 1000);
    }
    updateTime();
}

Online Code Part1

Explanation of the above code:

We created an automatic update time in the HTML page through the above JS code,

We don’t care about how to implement time update. Let’s see how we do dependency injection first; We areMyControllerThe parameter names set in this function are$scopeand$timeoutSo when the program runs to this function,AngularJSThe function object is called internallytoString()Method, assuming that the name of the parameter is the dependent name, analyze and extract the parameter list of the function, and then$injectorInject these parameters into the instance of the object.

Points needing attention:

  • With the above method only inAngularJSYou can run successfully only when your version is lower than 1.3.0.
  • This method is only suitable for uncompressed and obfuscated code becauseAngularJSThe original uncompressed parameter list is required for parsing.

2. Explicit injection declaration

AngularJSAn explicit locality method is provided to clearly define the dependencies that a function needs to use when called. By declaring dependencies in this way, it can work even when the source code is compressed and the parameter name is changed.

Here is a code example:

HTML code:

html<div ng-app>
    <div ng-controller="MyController">
        <p ng-cloak>{{clock.time | date: "yyyy-MM-dd hh:mm:ss"}}</p>
    </div>
</div>

JS code:

javascriptfunction MyController(s, t) {
    var updateTime = function () {
        s.clock = {
            time: new Date()
        };
        t(function () {
            s.clock.time = new Date();
            updateTime();
        }, 1000);
    }
    updateTime();
}
MyController["$inject"] = ["$scope", "$timeout"];

Online Code Part2

Explanation of the above code:

The parameter names we set for our function aresandt, and then we’ll use it laterMyController["$inject"] = ["$scope", "$timeout"];Explicitly inject the dependencies we need intoMyControllerIn function; So inMyControllerIn the function,srepresentative$scope,trepresentative$timeout, it doesn’t feel as hard as it sounds. We continue our dependency injection.

Points needing attention

  • For this declaration, the order of parameters is very important because$injectThe order of array elements must correspond to the order of injected parameters one by one.

There is another way to write the JS code above, as follows:

JS code:

javascriptvar MyControllerFactory = function MyController(s, t) {
    var updateTime = function () {
        s.clock = {
            time: new Date()
        };
        t(function () {
            s.clock.time = new Date();
            updateTime();
        }, 1000);
    }
    updateTime();
}
MyControllerFactory.$inject = ["$scope","$timeout"];

Note the in the HTML codeng-controllerNeed to be changed toMyControllerFactory

Online Code Part3

Inline injection declaration

AngularJSThe inline injection method provided is actually a syntax sugar, which is similar to the above-mentioned method$injectThe principle of attribute declaration is the same, but it allows us to pass in parameters from the line during function definition. This method is convenient and simple, and avoids the use of temporary variables in the definition process.

Here is a code example:

HTML code:

html<div ng-app="MyApp">
    <div ng-controller="MyController">
        <p ng-cloak>{{clock.time | date: "yyyy-MM-dd hh:mm:ss"}}</p>
    </div>
</div>

JS code:

javascriptangular.module("MyApp", [])
.controller("MyController", ["$scope", "$timeout", function (s, t) {
    var updateTime = function () {
        s.clock = {
            time: new Date()
        };
        t(function () {
            s.clock.time = new Date();
            updateTime();
        }, 1000);
    }
    updateTime();
}]);

Online Code Part4

Note that the inline declaration allows us to pass in an array of parameters directly instead of a function. The elements of the array are strings, which represent the dependency names that can be injected into the object. The last parameter is the object of the dependency injection function itself.

It’s been hereAngularJSThe dependency injection method is almost the same, but there is another point, that is, our above methods all rely on one service, that is$injector, I will discuss with you what this thing is.

Also, if you think some of the things I said above are wrong, please point it out and let’s make progress together^_^