我决定看一看 Angularjs。在教程的第一步之后,我尝试重命名 $scope
变量。但它打破了一切。
phonecatApp.controller('PhoneListCtrl', function($scope) { ... }); // this works
phonecatApp.controller('PhoneListCtrl', function(foo) { ... }); // this does not works
为什么?它不只是传递给回调的局部变量吗?为什么它必须具有特定名称?
它是注入(inject)变量。这意味着 Angular 实际上会从它的名字中推断出它的值。这就是为什么只有“$scope”会起作用。
这适用于 Controller 、服务等的任何参数。例如,如果您定义自己的服务,您也将注入(inject)它:
// You will not get instance of your service directly. Instead, just
// put it right into function parameter list, and it will get injected
// by Angular for you.
phonecatApp.controller('PhoneListCtrl', function ($scope, SomeService) {
});
// Declaration of your custom service.
phonecatApp.factory('SomeService', function() {
});
您将在 this article 中找到有关 Angular 中 DI(依赖项注入(inject))的更多信息.