Demo of my blog post: http://chrisgarvis.com/blog/screw-d3-js-bar-charts-in-angularjs.html
You can view at: http://bl.ocks.org/cgarvis/7794012
Demo of my blog post: http://chrisgarvis.com/blog/screw-d3-js-bar-charts-in-angularjs.html
You can view at: http://bl.ocks.org/cgarvis/7794012
(function() { | |
var app = angular.module('angular-charts', []); | |
app.controller('MainCtrl', function($scope, shuffle) { | |
$scope.dataset = [4, 4, 8, 15, 16, 23, 42]; | |
$scope.shuffle = function() { | |
$scope.dataset = shuffle($scope.dataset); | |
} | |
}); | |
app.factory('shuffle', function() { | |
return function(array) { | |
var tmp, current, top = array.length; | |
if(top) while(--top) { | |
current = Math.floor(Math.random() * (top + 1)); | |
tmp = array[current]; | |
array[current] = array[top]; | |
array[top] = tmp; | |
} | |
return array; | |
} | |
}); | |
app.directive('barChart', function($log) { | |
return { | |
restrict: 'E', | |
replace: true, | |
scope: { | |
dataset: '=' | |
}, | |
template: '<svg ng-attr-height="{{graph.height}}" ng-attr-width="{{graph.width}}"><rect ng-repeat="data in dataset track by $index" ng-attr-width="{{width()}}" ng-attr-height="{{height(data)}}" ng-attr-x="{{x($index)}}" ng-attr-y="{{graph.height - height(data)}}" fill="#2d578b"></rect></svg>', | |
link: function(scope, element, attrs) { | |
var padding = 1; | |
scope.graph = { | |
width: 400, | |
height: 200 | |
} | |
scope.width = function() { | |
var dataPoints = scope.dataset.length; | |
return (scope.graph.width - dataPoints * padding) / dataPoints; | |
} | |
scope.height = function(data) { | |
var max = Math.max.apply(null, scope.dataset); | |
return data / max * scope.graph.height; | |
} | |
scope.x = function(index) { | |
return index * padding + index * scope.width() | |
} | |
} | |
} | |
}); | |
})(); |
<!DOCTYPE html> | |
<html ng-app="angular-charts"> | |
<head> | |
<title>Angular Charts Demo</title> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js"></script> | |
<script src="angular-charts.js"></script> | |
<link rel="stylehseet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css"></link> | |
</head> | |
<body ng-controller="MainCtrl"> | |
<div class="container"> | |
<div class="row"> | |
<div class="col-md-2"> | |
<button ng-click="shuffle()">Shuffle</button> | |
</div> | |
<div class="col-md-4"> | |
<bar-chart dataset="dataset"></bar-chart> | |
</div> | |
</div> | |
</div> | |
</body> | |
</html> |