2016-12-16 3 views
2

Angular JS(1.5.8)の次のコントローラを考えてみましょう。このプロジェクトではWebCola 3.1.3とd3 3.4.11も使用しています。AngularJSモデルを扱うD3イベントがバインドに影響しないのはなぜですか?

$スコープの任意のプロパティをd3コールバックハンドラ関数の内側から変更しようとすると、そのバインディングはレンダリングされたHTMLでは無効になります。

どのようにしてこの動作がd3から防止され、2ウェイバインディングが正常に行われるかを把握するにはどうすればよいですか?あなたはD3イベントから値を更新する際

<div ng-controller="MainController"> 
    <h2>{{balls[0].a}}</h2> 
    <button ng-click="foo()">Do it!</button> 
</div> 

angular.module('nua').controller('MainController', ['$scope'], function ($scope) { 

    $scope.balls = []; 

    $scope.onCircleClickHandler = function (data, index) { 

     $scope.balls[index].a = 2; 

     // The problem is here! 
     // Every function of d3 that change the value 
     // of any scope property takes no effect in binding 

     // No one of my tries to change the value of any 
     // property of $scope.balls to see the rendered result 
     // in the <h2> takes effect. 

     // The value of $scope.balls[index].a is really 
     // updated to "2", but the values of <h2> remains "1". 

     // The calling from D3 seems to prevent something that affects binding. 

    }; 

    $scope.foo = function() { 

     $scope.balls[1].d = 5; 

     // This works properly. 

     // If I call onCircleClickHandler and THEN call foo, 
     // then the binding takes effect and <h2> has now the 
     // "2" as innerHTML 

    }; 

    $scope.init = function() { 

     // var mycola = cola.d3adaptor() ... 

     // var svg = d3.select('id') ... 

     // var nodes = svg.selectAll('circle') ... 

     nodes.on('click', function (data, index) { 

      this.onCircleClickHandler(data, index); 

     }.bind($scope)) 

     $scope.balls = [ 
      {a:1, b:2, c:3}, 
      {d:4, e:5, f:6} 
     ]; 

    }; 


}); 

答えて

0

理由があり、角度はスコープのデータが変更されたので、それがダイジェストサイクルを呼び出す必要があることを知って来ることはありません。

$scope.onCircleClickHandler = function (data, index) { 
     //this will notify angular that the scope value has changed. 
     $scope.$apply(function() { 
      $scope.balls[index].a = 2; 
     }); 

    }; 
+0

おかげで、シリル:

だから、この方法でなければなりません。完璧に動作します。私はそのドキュメントについてもっと読むつもりです。 – lordshark

関連する問題