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?
迷茫2017-06-10 09:50:17
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.