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?
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:
Since
$scope
and$rootScope
are both built-in services of AngularJS, AngularJS can find what you want to inject. But if you change it torootScope
, AngularJS won’t be able to find it from its own framework.If using explicit dependency injection, this is it:
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: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.