Example on how d3 transitions can be used in AngularJS
Last active
May 31, 2019 05:17
-
-
Save chrisirhc/10003441 to your computer and use it in GitHub Desktop.
d3 data transitions in AngularJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.module('exampleApp', []) | |
.controller('MainCtrl', function($scope, $interval) { | |
$scope.circles = [ | |
{x: 1, y:2, r: 4} | |
]; | |
var width = 500, height = 200; | |
function randCircle() { | |
return { | |
x: Math.random()*width, | |
y: Math.random()*height, | |
r: Math.random()*width/4, | |
color: d3.hsl(Math.random()* 360, 0.5, 0.5).toString() | |
}; | |
} | |
function getData() { | |
console.log('fill data'); | |
$scope.circles.length = 0; | |
for (var i = 0; i < 10; i++) { | |
$scope.circles.push(randCircle()); | |
} | |
} | |
var timer; | |
$scope.autoPlay = function () { | |
if (timer) { | |
$interval.cancel(timer); | |
timer = null; | |
} else { | |
timer = $interval(getData, 3000); | |
} | |
}; | |
$scope.transition = getData; | |
$scope.autoPlay(); | |
}) | |
.directive('transAttr', function () { | |
return { | |
link: function (scope, element, attr) { | |
var d3sel = d3.select(element[0]); | |
scope.$watchCollection(attr.transAttr, function (newAttrs) { | |
newAttrs = d3.entries(newAttrs); | |
var trans = d3sel.transition().duration(1000); | |
newAttrs.forEach(function (attr) { | |
trans.attr(attr.key, attr.value); | |
}); | |
}); | |
} | |
}; | |
}) | |
; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html ng-app="exampleApp"> | |
<head> | |
<title>AngularJS Plunker</title> | |
<script data-require="[email protected]" src="https://code.angularjs.org/1.2.13/angular.js" data-semver="1.2.13"></script> | |
<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script> | |
<script src="app.js"></script> | |
</head> | |
<body ng-controller="MainCtrl"> | |
<svg width="500" height="200"> | |
<circle ng-repeat="circle in circles track by $index" | |
trans-attr="{ | |
cx: circle.x, | |
cy: circle.y, | |
r: circle.r, | |
fill: circle.color | |
}" /> | |
</svg> | |
<button type="button" ng-click="transition()">Transition Now!</button> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment