【问题标题】:AngularJS: inject service into directive?AngularJS:将服务注入指令?
【发布时间】:2014-02-08 07:20:52
【问题描述】:

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

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

app.js:

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

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

var sentimentAppServices = angular.module('sentimentAppServices', ['ngResource'])
// other services
.factory('d3', [function(){
  var d3;
  d3 = // d3 library code here
  return d3; 
}]);

现在在directives.js:

var sentimentAppDirectives = angular.module('sentimentAppDirectives', ['sentimentAppServices']);

sentimentAppDirectives.directive('lsPieChart', ['d3', function($compile, d3){
   return {
     // scope & template
     link: function($scope, elem, attr, ctrl) {
       console.log(d3); // undefined
     }
   }

有什么建议吗?谢谢。

【问题讨论】:

    标签: javascript angularjs dependency-injection d3.js


    【解决方案1】:

    问题是你暗示的依赖与你实际传入的不匹配:

    ['$compile, d3', function($compile, d3
    

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

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

    app.directive('directiveName', function($compile, d3) {
      // ....
    });
    

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

     ['$compile, d3', function(a, b
    

    a 将设置为 $compile 服务,b 将设置为您的 d3 服务。

    【讨论】:

    • 请注意,如果您使用 ngmin 实用程序(如果在缩小之前执行此操作),您并不总是需要此操作,因为它会自动完成。这可以简化维护,因为您可能会意外遇到主题中描述的类似问题。
    猜你喜欢
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多