Step-by-step instructions on integrating d3.js as a dependency in an angular.js application can be found in this ng-newsletter article:
angular.module('d3', [])
.factory('d3Service', ['$document', '$q', '$rootScope',
function($document, $q, $rootScope) {
var d = $q.defer();
function onScriptLoad() {
// Load client in the browser
$rootScope.$apply(function() { d.resolve(window.d3); });
}
// Create a script tag with d3 as the source
// and call our onScriptLoad callback when it
// has been loaded
var scriptTag = $document[0].createElement('script');
scriptTag.type = 'text/javascript';
scriptTag.async = true;
scriptTag.src = 'http://d3js.org/d3.v3.min.js';
scriptTag.onreadystatechange = function () {
if (this.readyState == 'complete') onScriptLoad();
}
scriptTag.onload = onScriptLoad;
var s = $document[0].getElementsByTagName('body')[0];
s.appendChild(scriptTag);
return {
d3: function() { return d.promise; }
};
}]);
A similar approach can be used for any other JS library. For d3plus, the module/factory setup looks like this:
angular.module('d3plus', [])
.factory('d3plusService', ['$document', '$window', '$q', '$rootScope',
function ($document, $window, $q, $rootScope) {
var d = $q.defer(),
d3plusService = {
d3plus: function () {
return d.promise;
}
};
function onScriptLoad() {
// Load client in the browser
$rootScope.$apply(function () {
d.resolve($window.d3plus);
});
}
var scriptTag = $document[0].createElement('script');
scriptTag.type = 'text/javascript';
scriptTag.async = true;
scriptTag.src = 'path/to/d3plus.min.js';
scriptTag.onreadystatechange = function () {
if (this.readyState == 'complete') onScriptLoad();
};
scriptTag.onload = onScriptLoad;
var s = $document[0].getElementsByTagName('body')[0];
s.appendChild(scriptTag);
return d3plusService;
}]);
Remember to incorporate the promise functions in your d3/d3plus directives as shown below:
app.directive('myD3Directive', ['d3Service', 'd3plusService',
function(d3service, d3plusService) {
return {
restrict: 'E',
link: function(scope, elem, attrs) {
d3service.d3().then(function (d3) {
d3plusService.d3plus().then(function (d3plus) {
// Your code goes here
}
}
}
}
}
]);