2016-07-29 22 views
1

私はAngularJSと私のd3.jsコードを統合しようとしていると私は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は定義されていません。データをディレクティブに渡すと、同じ結果になります。

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

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

私はで自分自身を鼓舞しようとした: 私は簡単な答えがあるように感じるが、私はそれを把握することはできません...ここ

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

そして、私の指示の上の部分ですhttp://bl.ocks.org/vicapow/9496218

+2

'd3.json'は非同期で、' console.log($ scope.root); 'は関数コールバックの外にあり、コールバックが起動する前に実行されます。 – Mark

答えて

0

私のディレクティブのルート変数にウォッチを置くことで、機能の非同期性が指摘されたので、console.logが定義されていないように動作させることができました。ディレクティブに$ watchを設定し、ルートが定義されていないときにのみ動作することが、このトリックでした!