Reputation: 4083
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
The tutorial creates a d3 module which contains d3Service
, and that gets injected into a directive. 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. I can inject the d3 service into my controller without issue. Here's what I'm doing:
app.js
:
var sentimentApp = angular.module('sentimentApp', [
'ngRoute',
'ngSanitize',
'sentimentAppServices',
'sentimentAppDirectives',
'sentimentAppControllers'
]);
Within services.js
, I have several services, one of which is 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
:
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.
Upvotes: 5
Views: 20261
Reputation: 43785
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
.
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:
['$compile, d3', function(a, b
a
will be set to the $compile
service and b
to your d3
service.
Upvotes: 12