D3.js and AngularJS directives

AngularJs + d3Js + bar chart example usign directives

by SleepyProgrammer

HTML

<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<div ng-app="myApp" ng-controller="Ctrl">
    
    <div ng-repeat="object in myData">
     <div id="obj{{object.id}}">
     Hi
    <bars-chart></bars-chart>
    </div>
  </div> 
</div>

JavaScript

angular.module('myApp', []).
   //camel cased directive name
   //in your HTML, this will be named as bars-chart
   directive('barsChart', function ($parse) {
     //explicitly creating a directive definition variable
     //this may look verbose but is good for clarification purposes
     //in real life you'd want to simply return the object {...}
     var directiveDefinitionObject = {
         restrict: 'E',
         link: function (scope, element, attrs) {
             var obj = scope.object;
           //in D3, any selection[0] contains the group
           //selection[0][0] is the DOM node
           //but we won't need that this time
           var test = d3.selectAll("div");
           console.log(test);
           var chart = d3.select("#obj" +obj.id);
           console.log(chart);
         } 
      };
      return directiveDefinitionObject;
   });

function Ctrl($scope) {
    $scope.myData = [ {"id":"1"}, {"id":"2"}];
}