亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

javascript - How does angularjs know what parameters are required in the callback function?
歐陽克
歐陽克 2017-06-10 09:48:17
0
1
1045

For example:

app.controller('myCtrl', function($scope, $rootScope) {
    // 將$rootScope改成其他名字就不行了。
    $scope.names = ["Emil", "Tobias", "Linus"];
    $rootScope.lastname = "Refsnes";
});

How does angular know that my second parameter requires $rootScope?

歐陽克
歐陽克

溫故而知新,可以為師矣。 博客:www.ouyangke.com

reply all(1)
迷茫

Because AngularJS provides two injection methods. One is called implicit dependency injection (implicit dependency injection), and the other is called explicit dependency injection (explicit dependency injection).

In your code, you use the first type, implicit dependency injection:

app.controller('myCtrl', function($scope, $rootScope) {
    $scope.names = ["Emil", "Tobias", "Linus"];
    $rootScope.lastname = "Refsnes";
});

Since $scope and $rootScope are both built-in services of AngularJS, AngularJS can find what you want to inject. But if you change it to rootScope, AngularJS won’t be able to find it from its own framework.

If using explicit dependency injection, this is it:

app.controller('myCtrl', ['$scope', '$rootScope', function(whatever, blah) {
    whatever.names = ["Emil", "Tobias", "Linus"];
    blah.lastname = "Refsnes";
}]);

This way AngularJS will look for it based on the explicitly declared $scope and $rootScope. Then it doesn't matter what you set in the parameters of the anonymous function. Just pay attention to the order.

Alternatively, you can also do it by calling $inject manually. Like this:

var myController = function($scope, $rootScope) {
    $scope.names = ["Emil", "Tobias", "Linus"];
    $rootScope.lastname = "Refsnes";
});

myConroller.$inject = ['$scope', '$rootScope'];

app.controller('myCtrl', myController);

Please refer to the documentation for details: https://docs.angularjs.org/gu...
Dependency Annotation part.

The documentation also reminds you that if you plan to compress your code, don't use implicit dependency injection.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template