Skip to content

Instantly share code, notes, and snippets.

@whippersnapper
Created August 12, 2014 19:18
Show Gist options
  • Save whippersnapper/f74103c02840c9e02a2f to your computer and use it in GitHub Desktop.
Save whippersnapper/f74103c02840c9e02a2f to your computer and use it in GitHub Desktop.
D3js Directive Wrapper
'use strict';
angular.module('demoapp')
.directive('donut', function () {
return {
restrict: 'E',
scope: {
data: '='
},
link: function postLink(scope, element, attrs) {
var data = scope.data;
var width = 960,
height = 500,
radius = Math.min(width, height) / 2;
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c"]);
var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(radius - 120);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.value; });
var svg = d3.select(element[0])
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var render = function(data) {
data.forEach(function(d) {
d.value = +d.value;
});
var g = svg.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
.style("fill", function(d) { return color(d.data.label); });
g.append("text")
.attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
.attr("dy", ".35em")
.style("text-anchor", "middle")
.text(function(d) { return d.data.label; });
};
scope.$watch('data', function(){
if(scope.data) {
render(scope.data);
}
}, true);
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment