Skip to content

Instantly share code, notes, and snippets.

@cgarvis
Last active December 30, 2015 07:09
Show Gist options
  • Save cgarvis/7794012 to your computer and use it in GitHub Desktop.
Save cgarvis/7794012 to your computer and use it in GitHub Desktop.
(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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment