我理解Angular依赖注入是如何与指令一起工作的,但我想澄清一些事情。我有一个虚拟测试指令如下:
app.directive("test", [
function() {
return {
restrict: "E",
scope: {},
controller: ["$scope", "$filter",
function($scope, $filter) {
var food = ["Apple pie", "Apple cobler", "Banana Split", "Cherry Pie", "Applesauce"];
$scope.favorites = $filter('filter')(food, "Apple");
}
],
template: "<div>{{favorites}}</div>"
}
}
]);
这很好,将按预期过滤food
数组。然而,我注意到,如果我在指令中注入$filter
服务,它仍然有效:
app.directive("test", ["$filter",
function($filter) {
return {
restrict: "E",
scope: {},
controller: ["$scope",function($scope) {...
我的问题是:像这样在声明行中将服务注入到指令中是否更好:
app.directive("test", ["$filter", function($filter) {
或者像这样在控制器行中:
controller: ["$scope", "$filter", function($scope, $filter) {
?
没有区别吗?这是一个普朗克的指令代码。
在本例中,您接收的是相同的服务,因此这可能无关紧要。我个人更倾向于让它们尽可能本土化;如果你不需要$filter
在link
函数或类似的东西,我就把它注入到控制器。
在某些情况下,这也可以使在测试期间模拟依赖关系更容易。
您也可以这样做。更好的方法是将指令和它的控制器拆分到一个文件中。或者您可以在单独的文件中写入。但是,更好地理解
app.directive('throbberDirective',
[
function(){
return {
restrict: "EA",
templateUrl: "common/utils/throbbers/throbber.html",
controller: throbberController
}
}
]);
app.controller('throbberController', throbberController);
throbberController.$inject = ['$scope', '_$ajax'];
function throbberController($scope){
$scope.throbber = _$ajax.getThrobberConfigs();
$scope.throbber.templateName = $scope.throbber.templateName;
}