D3JS line chart with Angular - v3.1
by Rishabh Sharma
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.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>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<div ng-controller="MyCtrl as vm">
<line-chart data="vm.data" lines="vm.lines"></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) {
var vm = this;
vm.controls1 = ["primary", "secondary"];
vm.lines = ["primary", "secondary"];
vm.data = [{
"date": "1-Apr-11",
"primary": 9997,
"secondary": 9324
}, {
"date": "1-May-11",
"primary": 10244,
"secondary": 9729
}, {
"date": "1-Jun-11",
"primary": 10345,
"secondary": 9921
}];
})
.directive('lineChart', function($window) {
return {
restrict: 'E',
replace: true,
scope: {
data: '=',
lines: '='
},
template: '<div id="chart"></div>',
link: function(scope, element, attrs, fn) {
var d3 = $window.d3;
var lineChart = (function() {
var rawData, chartData, filteredData;
var object = {};
// Set the dimensions of the canvas / graph
var margin = {
top: 30,
right: 80,
bottom: 50,
left: 50
},
width = 600 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;
// Adds the svg canvas
var svg = d3.select(element[0])
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
var g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// 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)
.innerTickSize(-height)
.outerTickSize(0)
.tickPadding(10);
var...