javascript - AngularJS:将服务注入(inject)指令?

标签 javascript angularjs dependency-injection d3.js

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

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

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
     }
   }

有什么建议吗?谢谢。

最佳答案

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

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

因此,您所做的是将 d3 服务作为变量 $compile 传递,而不是将任何内容作为变量 d3 传递。

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

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

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

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

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

关于javascript - AngularJS:将服务注入(inject)指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21211695/

相关文章:

javascript - 如何防止使用 jQuery 单击弹出窗口时关闭弹出窗口?

javascript - 使用淡入淡出 jQuery 的图像切换

javascript - AngularJS 使用作用域变量解析 JSON 数据

javascript - AngularJS 中的循环编号验证

c# - transient 组件注册为 transient 但实现了 idisposable

Javascript 实例上下文原型(prototype)

javascript - 如何根据 joomla 3.x 中的多个选择框显示和隐藏文本框

javascript - 传递数组中的 Angular 匹配值与页面上循环中的项目

c# - 如何使用 DI 将自定义授权添加到 WCF Web 服务

java - 无法刷新注入(inject)到 JSF 2 Managed Bean 中的 JPA 2 实体