D3js with Angular
D3 Donut Chart
by Rishabh Sharma
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<div ng-controller="MyCtrl as vm">
<div class="legend">
<span ng-repeat="(key,val) in vm.legend">
<svg height="20" width="20">
<rect x="0" y="0" width="20" height="20" stroke-width="1" fill="{{val}}" />
</svg>
{{key}}
</span>
</div>
<donut-chart style="padding: 20px" data="vm.data"></donut-chart>
</div>
CSS
body {
font-family: Calibri;
}
JavaScript
angular.module('myApp', [])
.controller('MyCtrl', function($scope) {
this.data = {
caption: "",
values: {
Chrome: -61,
Safari: -4,
Opera: -2
}
};
this.legendColors = ["#FF7029", "#FFE666", "#009CEB", "#009980", "#FFB300", "#00CCFF"];
this.legend = {};
this.legendKeys = Object.keys(this.data.values);
for (var i = 0; i < this.legendKeys.length; i++) {
this.legend[this.legendKeys[i]] = this.legendColors[i]
}
})
.directive('donutChart', function($window) {
return {
restrict: 'E',
replace: true,
scope: {
data: '='
},
template: '<div id="chart"></div>',
link: function(scope, element, attrs, fn) {
var d3 = $window.d3;
function donut() {
// Default settings
var $el = d3.select("body");
var data = {};
// var showTitle = true;
var width = 175,
height = 175,
radius = Math.min(width, height) / 2;
var currentVal;
function getPositiveColors(n) {
var colors = ["#FF7029", "#FFE666", "#009CEB"];
return colors[n % colors.length];
}
function getNegativeColors(n) {
var colors = ["#009980", "#FFB300", "#00CCFF"];
return colors[n % colors.length];
}
var color = d3.scale.category20();
var pie = d3.layout.pie()
.sort(null)
.value(function(d) {
return d.value;
});
var svg, g, arc;
var object = {};
// Method for render/refresh graph
object.render = function() {
if (!svg) {
arc = d3.svg.arc()
.outerRadius(radius)
.innerRadius(radius - (radius / 2.5));
arcOuter = d3.svg.arc()
.outerRadius(20)
.innerRadius(radius - (40));
svg =...