AngularJS和D3.js V4,d3.json问题

时间:2016-07-29 14:24:54

标签: angularjs json d3.js d3.js-v4

我正在尝试将我的d3.js代码与AngularJS集成,我遇到了d3.json函数的问题

    var OrgChartApp = angular.module('OrgChartApp', []);

//APP CONTROLLER
OrgChartApp.controller('OrgChartCtrl', function ($scope, $window) {

  var i = 0,
      stratify,
      data,
      tree;                                                                                                                

  data = d3.json("orgChartDataSMALL.json",function(error, data){

    if(error) throw error;
    $scope.$apply(function(){//Setting up data for stratification by indicating what will be the parent and children nodes
      console.log('applying');
      stratify = d3.stratify()
                    .id(function(d) {return d.FullName;})//Position
                    .parentId(function(d) {return d.Manager;});//Manager's position

      $scope.root = stratify(data); //Transforming linear data into hierarchical data

      //Data needs slight remapping before feeding it into tree layout.
      $scope.root.each(function(d) {

        d.name = d.id; //transferring name to a name variable
        d.id = i; //Assigning numerical Ids
        i++;
        /*Calculating the numbers of employe under managers*/ 
       d.headcount = getDescendants(d); 
      }); 

    });

  });  

  console.log($scope.root);//THIS COMES BACK AS UNDEFINED

  //This function allows to figure out, how many employee are under a manager.
  function getDescendants(node) {
          if(!node.children && !node._children) {
              return 0;
          }
          var total = 0;

          if(node.children){
              node.children.forEach(function(d) {
              total += 1+getDescendants(d);
            })
          }else if(node._children){
              node._children.forEach(function(d) {
              total += 1+getDescendants(d); 
            })
          }

          return total;
      }                                     

});

d3.json下的console.log以未定义的形式返回,当我将数据传递给我的指令时,我得到了同样的结果。 我觉得有一个简单的答案,但我无法弄清楚......

<div ng-App='OrgChartApp' ng-controller="OrgChartCtrl">
    <!-- Here's where our visualization will go -->
    <ochart-visualization root="root"></ochart-visualization>
</div>

这是我指令的最重要部分:

//APP DIRECTIVES
OrgChartApp.directive('ochartVisualization',function($window, $document){

  return {
    restrict: 'E',
    scope: {
      root:  '='
    },
    link: function ( scope, element ) {

我试图通过http://bl.ocks.org/vicapow/9496218

激励自己

1 个答案:

答案 0 :(得分:0)

通过在我的指令中对根变量进行监视,我能够使其工作,因为标记指出函数的异步性质使得它因为console.log未定义。在指令中设置$ watch并且仅在root未定义时才执行操作就行了!