直接将服务注入AngularJS指令控制器 [英] Injecting services into AngularJS directive controller directly

查看:58
本文介绍了直接将服务注入AngularJS指令控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解Angular依赖注入如何与指令一起使用,但需要澄清某些内容。我有一个虚拟测试指令如下:

I understand how Angular dependency injection works with directives but wanted clarification on something. I have a dummy test directive as follows:

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>"
    }
  }
]);

此工作正常,将过滤食物数组如预期。但是我注意到如果我在指令中注入 $ filter 服务,它仍然有效:

This works fine and will filter the food array as expected. However I noticed if I inject the $filter service in the directive as follows, it still works:

app.directive("test", ["$filter",

  function($filter) {

    return {
      restrict: "E",
      scope: {},
      controller: ["$scope",function($scope) {...

我的问题:最好将服务注入声明行中的指令,如下所示:

My question: Is it better practice to inject services into a directive in the declaration line like so:

app.directive(test,[$ filter,函数($ filter){

或在这样的控制器行:

控制器:[$ scope,$ filter,函数($ scope,$ filter){

没有区别吗?这是 Plunker

推荐答案

在这种情况下,你收到了相同的服务,所以它可能不会太多了。我个人更喜欢让它们尽可能地本地化;如果您在链接函数中不需要 $ filter 或类似的东西,我只需将其注入控制器。

In this case, you're receiving the same service, so it likely doesn't matter too much. I personally prefer to keep them as localized as possible; if you don't need $filter in the link function or something like that, I'd just inject it into the controller.

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

In certain cases, this may also make it easier to mock dependencies during testing.

这篇关于直接将服务注入AngularJS指令控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆