Skip to content

Instantly share code, notes, and snippets.

@sunnycyk
Last active January 1, 2016 04:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunnycyk/8093331 to your computer and use it in GitHub Desktop.
Save sunnycyk/8093331 to your computer and use it in GitHub Desktop.
Using d3 with dependency injection
angular.module('d3', [])
.provider('d3Service', function() {
function createScript($document, callback, success) {
var scriptTag = $document.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') {
callback();
}
}
scriptTag.onload = callback;
$document.getElementsByTagName('body')[0].appendChild(scriptTag);
}
this.$get = ['$document','$q', '$window', '$rootScope',
function($document, $q, $window, $rootScope) {
var deferred = $q.defer();
createScript($document[0], function(callback) {
$rootScope.$apply(function() { deferred.resolve($window.d3) });;
})
return deferred.promise;
}];
});
angular.module('directive.linechart', ['d3'])
.directive('lineChart',['d3Service', function(d3Service) {
return {
// Directive options
link: function(scope, element, attr) {
d3Service.then(function(d3) {
// now you can use d3 as usual!
});
}
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment