【发布时间】:2013-10-14 19:33:02
【问题描述】:
我刚开始学习 Angular.js,一直在看project.js in the "Wire up a Backend" example on the Angular home page。
我对控制器函数中的参数感到困惑:
function ListCtrl($scope, Projects) {
...
}
function CreateCtrl($scope, $location, $timeout, Projects) {
...
}
function EditCtrl($scope, $location, $routeParams, angularFire, fbURL) {
angularFire(fbURL + $routeParams.projectId, $scope, 'remote', {}).
then(function() {
...
});
}
这些控制器函数在routeProvider中被调用,但是没有给出任何参数。
$routeProvider.
when('/', {controller:ListCtrl, templateUrl:'list.html'}).
when('/edit/:projectId', {controller:EditCtrl, templateUrl:'detail.html'}).
when('/new', {controller:CreateCtrl, templateUrl:'detail.html'}).
otherwise({redirectTo:'/'});
});
到目前为止,我能找到的唯一可能解释发生了什么的事情是"Injecting Services Into Controllers",它解释了$location、$timeout,但不是参数方法angularFire 和fbURL。
我的具体问题是:
控制器参数可以是什么?
在哪里调用带有参数的控制器函数?或者参数没有被调用,而只是与控制器相关联的东西,其中关联发生了很多 Angular.js 魔术(如果是这样,我可以在 github 上查看源代码)吗?
angularFire在哪里定义?-
参数中的
fbURL如何链接到:angular.module('project', ['firebase']). value('fbURL', 'https://angularjs-projects.firebaseio.com/'). factory ... 有没有可以看到所有服务的地方,例如
$location和$timeout,Angular.js 提供的? (我试图找到列表但失败了。)
【问题讨论】:
-
5.有关 Angular 中包含的所有内置服务、过滤器、指令的列表,请查看 API:docs.angularjs.org/api
-
4.就像您似乎理解的那样,控制器的参数是从控制器的定义中通过角度注入的。 Angular 会查看所有注册的服务,并尝试找到与指定参数名称匹配的参数并注入相应的服务!
-
3.定义项目模块时,还包括了 firebase 模块依赖项。在 firebase 模块内部,必须有一个像之前的 fbURL 一样的 angularFire 服务。
-
2.这是定义控制器的正确方法:
angular.module('project').controller('EditCtrl', ['$scope', '$location', '$routeParams', 'angularFire', 'fbURL', function($scope, $location, $routeParams, angularFire, fbURL) { ... } ]);这样,您首先设置要注入的服务的名称,然后根据需要为这些服务指定不同的名称。事实上,如果你想稍后最小化你的 Angular 代码,这是强制性的(因为最小化会重命名变量,所以 Angular 仍然需要能够找到服务名称)。 -
@jpmorin 只需添加您的 cmets 作为答案,它们都是正确的。
标签: angularjs