简体   繁体   English

AngularJS-如何在指令中使用服务

[英]AngularJS - How to use a service from within a directive

I'm trying to get my head around scopes and after dredging through a number of blogs, stack overflow answers and the docs I am still stuck. 我试图绕过范围,在疏通了许多博客,堆栈溢出答案和我仍然陷入困境的文档之后。

angular.module('app', [])
  .factory('alphabet', function () {
    data = [
      'c', 
      'b',
      'a'
    ];

    return {
      get : function () {
        return data;
      },
      set : function (val) {
        data.push(val);
      }
    };
  })
  .controller('AlphaCtrl', function (alphabet) {
    this.alphabet = alphabet;
  })
  .directive('sortableTable', function () {
    return {
      scope : {
         "param" : '@'
      },

      link : function (scope) {
        console.log(scope.param);
      }
    };
  })
;

HTML: HTML:

<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <div ng-controller="AlphaCtrl as alpha">
    <table sortable-table param="{{alpha.alphabet}}">
      <thead>
        <tr>
          <td></td>
          <td></td>
          <td></td>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
  </div>
</body>
</html>

What I would like to do is be able to access a service/factory that's being used in an outer controller from within a directive. 我想做的是能够从指令中访问外部控制器中正在使用的服务/工厂。 So for example when I handle a click event I can add items to the data. 因此,例如,当我处理点击事件时,我可以向数据中添加项目。 That seems to be a good way of keeping things decoupled but I am open to suggestions there. 这似乎是使事情脱钩的好方法,但是我愿意接受那里的建议。

The problem at hand is that 'param' is undefined. 当前的问题是“参数”是不确定的。 I've also tried using '&' but that's not doing anything for me. 我也尝试使用'&',但这对我没有任何帮助。 Could someone put me on the path to Angular righteousness? 有人可以让我走上正义之路吗?

I would inject the service directly into the directive: 我将服务直接注入到指令中:

.directive('sortableTable', function (alphabet) {
   return {
     scope : {},

     link : function (scope) {
       console.log(alphabet);
     }
   };
})

This is indeed a good way of keeping things decoupled, if this is a directive that is used across controllers and views. 如果这是跨控制器和视图使用的指令,那么这确实是使事物保持脱钩的好方法。


Edit for a bit more complex solution: It is possible to do it by injecting the service into the scope of the directive, though I would not recommend it if you don't need to switch services on the fly, since the method above is easier. 编辑复杂一点的解决方案: 可以通过注射服务到指令的范围去做,虽然我不会推荐它,如果你不需要在飞行中切换服务,因为上面的方法更容易。 I could see some use cases though, if you would want to input a different service (with the same get/set structure) in another controller for example. 我可以看到一些用例,例如,如果您想在另一个控制器中输入不同的服务(具有相同的获取/设置结构)。 Here's how you could do it via scope: 通过范围的方法如下:

.controller('myController', function($scope, alphabet) {
    $scope.alphabet = alphabet;
})
.directive('myDirective', function(){
    return {
        scope: {
            service: '='
        },
        template: '<div ng-bind="service.get()"></div>'
    }
})

And in the template: 并在模板中:

<div data-my-directive service="alphabet"></div>

The trick here is using service: '=' as this creates a two-way binding between the scope-variable in the controller (which is bound to the service) and the scope-variable in the directive. 这里的窍门是使用service: '='因为这会在控制器(绑定到服务)的范围变量和指令中的范围变量之间创建双向绑定。 http://jsfiddle.net/vt52bauu/2/ http://jsfiddle.net/vt52bauu/2/

我认为get / set不会像您在Angular工厂中所期望的那样工作。

this.alphabet = alphabet.get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM