我了解 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) {
?
有没有区别?这里有一个Plunker http://plnkr.co/edit/6aa0fFbEmkPXNeGwa6AC?p=preview指令代码。