D3JS line chart with Angular
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>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js"></script>
<div ng-controller="MyCtrl as vm">
<line-chart data="vm.data"></line-chart>
</div>
CSS
body {
font: 12px Arial;
}
path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}
.axis path,
.axis line {
fill: none;
stroke: grey;
stroke-width: 1;
shape-rendering: crispEdges;
}
div.tooltip {
position: absolute;
text-align: center;
width: 60px;
height: 28px;
padding: 2px;
font: 12px sans-serif;
background: lightsteelblue;
border: 0px;
border-radius: 8px;
pointer-events: none;
}
JavaScript
angular.module('myApp', [])
.controller('MyCtrl', function($scope) {
this.data = [{
"date": "1-Apr-11",
"primary": 58.13,
"secondary": 28.13
}, {
"date": "1-May-11",
"primary": 53.98,
"secondary": 35.13
}, {
"date": "1-Jun-11",
"primary": 67,
"secondary": 32.11
}, {
"date": "1-Jul-11",
"primary": 89.7,
"secondary": 32.11
}];
})
.directive('lineChart', function($window) {
return {
restrict: 'E',
replace: true,
scope: {
data: '='
},
template: '<div id="chart"></div>',
link: function(scope, element, attrs, fn) {
var d3 = $window.d3;
// Set the dimensions of the canvas / graph
var margin = {
top: 30,
right: 20,
bottom: 30,
left: 50
},
width = 600 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;
// Parse the date / time
var parseDate = d3.time.format("%d-%b-%y").parse;
var formatTime = d3.time.format("%e %B");
// Set the ranges
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
// Define the axes
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(5);
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);
// Define the line
// Define the div for the tooltip
var div = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
// Adds the svg canvas
var svg = d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// render the data
...