|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +/** |
| 4 | + * @ngdoc directive |
| 5 | + * @name whatamiApp.directive:simpleLineChart |
| 6 | + * @description |
| 7 | + * # simpleLineChart |
| 8 | + */ |
| 9 | +angular.module('whatamiApp') |
| 10 | + .directive('simpleLineChart', ['d3Service', function(d3Service) { |
| 11 | + return { |
| 12 | + restrict: 'EA', |
| 13 | + scope: {}, |
| 14 | + link: function(scope, element, attrs) { |
| 15 | + d3Service.d3().then(function(d3) { |
| 16 | + |
| 17 | + var margin = {top: 20, right: 20, bottom: 30, left: 50}, |
| 18 | + width = 600 - margin.left - margin.right, |
| 19 | + height = 700 - margin.top - margin.bottom; |
| 20 | + |
| 21 | + var parseDate = d3.time.format('%d-%b-%y').parse; |
| 22 | + |
| 23 | + var x = d3.time.scale() |
| 24 | + .range([0, width]); |
| 25 | + |
| 26 | + var y = d3.scale.linear() |
| 27 | + .range([height, 0]); |
| 28 | + |
| 29 | + var xAxis = d3.svg.axis() |
| 30 | + .scale(x) |
| 31 | + .orient('bottom'); |
| 32 | + |
| 33 | + var yAxis = d3.svg.axis() |
| 34 | + .scale(y) |
| 35 | + .orient('left'); |
| 36 | + |
| 37 | + var line = d3.svg.line() |
| 38 | + .x(function(d) { return x(d.date); }) |
| 39 | + .y(function(d) { return y(d.close); }); |
| 40 | + |
| 41 | + var svg = d3.select(element[0]).append('svg') |
| 42 | + .attr('width', width + margin.left + margin.right) |
| 43 | + .attr('height', height + margin.top + margin.bottom) |
| 44 | + .append('g') |
| 45 | + .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); |
| 46 | + |
| 47 | + // Hard coded data |
| 48 | + scope.data = [ |
| 49 | + {date: '4-Apr-12', close: 34}, |
| 50 | + {date: '5-Apr-12', close: 45}, |
| 51 | + {date: '6-Apr-12', close: 37}, |
| 52 | + {date: '7-Apr-12', close: 56}, |
| 53 | + {date: '8-Apr-12', close: 50}, |
| 54 | + {date: '9-Apr-12', close: 77} |
| 55 | + ]; |
| 56 | + |
| 57 | + scope.data.forEach(function(d) { |
| 58 | + d.date = parseDate(d.date); |
| 59 | + d.close = +d.close; |
| 60 | + }); |
| 61 | + |
| 62 | + x.domain(d3.extent(scope.data, function(d) { return d.date; })); |
| 63 | + y.domain(d3.extent(scope.data, function(d) { return d.close; })); |
| 64 | + |
| 65 | + svg.append('g') |
| 66 | + .attr('class', 'x axis') |
| 67 | + .attr('transform', 'translate(0,' + height + ')') |
| 68 | + .call(xAxis); |
| 69 | + |
| 70 | + svg.append('g') |
| 71 | + .attr('class', 'y axis') |
| 72 | + .call(yAxis) |
| 73 | + .append('text') |
| 74 | + .attr('transform', 'rotate(-90)') |
| 75 | + .attr('y', 6) |
| 76 | + .attr('dy', '.71em') |
| 77 | + .style('text-anchor', 'end') |
| 78 | + .text('Price ($)'); |
| 79 | + |
| 80 | + svg.append('path') |
| 81 | + .datum(scope.data) |
| 82 | + .attr('class', 'line') |
| 83 | + .attr('d', line); |
| 84 | + }); |
| 85 | + }}; |
| 86 | + }]); |
0 commit comments