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

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

问题描述:

我想我d3.js代码AngularJS整合和我有下d3.json功能AngularJS和D3.js V4,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; 
     }          

}); 

的的console.log问题d3.json回到未定义状态,当我将数据传递给我的指令时,我得到了相同的结果。 我觉得有一个简单的答案,但我不出来...

<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

+2

'd3.json'是异步的,你的'console.log($ scope.root);'在函数回调之外,并且会在回调触发前执行。 – Mark

通过在我的指令中加入一个监视根变量,我能够使其工作,因为标记指出函数的异步性质使得它的console.log未定义。在指令中设置一个$ watch,并且只在root没有被定义时才动作!