2016-07-29 184 views
1

我想我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

回答

0

通過在我的指令中加入一個監視根變量,我能夠使其工作,因爲標記指出函數的異步性質使得它的console.log未定義。在指令中設置一個$ watch,並且只在root沒有被定義時才動作!