[英]AngularJS: inject service into directive?
I've been trying to integrate D3.js with Angular, and am following this tutorial: http://www.ng-newsletter.com/posts/d3-on-angular.html 我一直在尝试将D3.js与Angular集成,并遵循本教程: http : //www.ng-newsletter.com/posts/d3-on-angular.html
The tutorial creates a d3 module which contains d3Service
, and that gets injected into a directive. 本教程创建了一个包含
d3Service
的d3模块,并将其注入到指令中。 My app has a slightly different structure, but whenever I try to inject the d3 service, it shows up as undefined
in my directive link
function. 我的应用程序结构略有不同,但每当我尝试注入d3服务时,它在我的指令
link
函数中显示为undefined
。 I can inject the d3 service into my controller without issue. 我可以毫无问题地将d3服务注入我的控制器。 Here's what I'm doing:
这是我正在做的事情:
app.js
: app.js
:
var sentimentApp = angular.module('sentimentApp', [
'ngRoute',
'ngSanitize',
'sentimentAppServices',
'sentimentAppDirectives',
'sentimentAppControllers'
]);
Within services.js
, I have several services, one of which is d3: 在
services.js
,我有几个服务,其中一个是d3:
var sentimentAppServices = angular.module('sentimentAppServices', ['ngResource'])
// other services
.factory('d3', [function(){
var d3;
d3 = // d3 library code here
return d3;
}]);
Now in directives.js
: 现在在
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
}
}
Any tips? 有小费吗? Thanks.
谢谢。
The problem is that your hinted dependencies don't match up to what you're actually passing in: 问题是您的暗示依赖项与您实际传入的内容不匹配:
['$compile, d3', function($compile, d3
So, what you were doing is passing the d3
service as the variable $compile
and not passing anything as the variable d3
. 所以,你所做的是将
d3
服务作为变量$compile
传递,而不是将任何东西作为变量d3
传递。
It might help you to understand what this is for. 它可能会帮助您理解这是为了什么。 In non-minified code, you could take out that array wrapper altogether, like this:
在非缩小代码中,您可以完全取出该数组包装器,如下所示:
app.directive('directiveName', function($compile, d3) {
// ....
});
The point of passing the names as a string is because strings won't be affected by minification. 将名称作为字符串传递的要点是因为字符串不会受到缩小的影响。 This means that angular will know how to inject the right dependencies in a case like this:
这意味着angular将知道如何在这种情况下注入正确的依赖项:
['$compile, d3', function(a, b
a
will be set to the $compile
service and b
to your d3
service. a
将设置为$compile
服务, b
将设置为d3
服务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.