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

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!