直接将服务注入AngularJS指令控制器

时间:2014-08-04 03:32:49

标签: javascript angularjs

我理解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

2 个答案:

答案 0 :(得分:13)

在这种情况下,您接受相同的服务,因此可能并不重要。我个人更喜欢让它们尽可能地本地化;如果您在$filter函数中不需要link或类似的东西,我只需将其注入控制器。

在某些情况下,这也可能使测试过程中更容易模拟依赖关系。

答案 1 :(得分:3)

你也可以这样做。将指令及其控制器拆分到单个文件中的方法要好得多。或者您可以在单独的文件中编写。但是,更好地理解

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;

}
相关问题