javascript – AngularJS:将服务注入指令?

前端之家收集整理的这篇文章主要介绍了javascript – AngularJS:将服务注入指令?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我一直在尝试将D3.js与Angular集成,并遵循本教程:
http://www.ng-newsletter.com/posts/d3-on-angular.html

本教程创建了一个包含d3Service的d3模块,并将其注入到指令中.我的应用程序结构略有不同,但每当我尝试注入d3服务时,它在我的指令链接函数显示为未定义.我可以毫无问题地将d3服务注入我的控制器.这是我正在做的事情:

app.js:

  1. var sentimentApp = angular.module('sentimentApp',[
  2. 'ngRoute','ngSanitize','sentimentAppServices','sentimentAppDirectives','sentimentAppControllers'
  3. ]);

在services.js中,我有几个服务,其中一个是d3:

  1. var sentimentAppServices = angular.module('sentimentAppServices',['ngResource'])
  2. // other services
  3. .factory('d3',[function(){
  4. var d3;
  5. d3 = // d3 library code here
  6. return d3;
  7. }]);

现在在directives.js中:

  1. var sentimentAppDirectives = angular.module('sentimentAppDirectives',['sentimentAppServices']);
  2. sentimentAppDirectives.directive('lsPieChart',['d3',function($compile,d3){
  3. return {
  4. // scope & template
  5. link: function($scope,elem,attr,ctrl) {
  6. console.log(d3); // undefined
  7. }
  8. }

有小费吗?谢谢.

最佳答案
问题是您的暗示依赖项与您实际传入的内容不匹配:

  1. ['$compile,d3',d3

所以,你所做的是将d3服务作为变量$compile传递,而不是将任何东西作为变量d3传递.

它可能会帮助您理解这是为了什么.在非缩小代码中,您可以完全取出该数组包装器,如下所示:

  1. app.directive('directiveName',d3) {
  2. // ....
  3. });

名称作为字符串传递的要点是因为字符串不会受到缩小的影响.这意味着angular将知道如何在这种情况下注入正确的依赖项:

  1. ['$compile,function(a,b

a将设置为$compile服务,b将设置为d3服务.

猜你在找的JavaScript相关文章