2
考慮下面的Angular JS控制器(1.5.8)。該項目也使用WebCola 3.1.3和d3 3.4.11。爲什麼處理AngularJS模型的D3事件對綁定沒有影響?
當我嘗試從d3回調處理函數中更改我的$ scope的任何屬性時,該綁定在呈現的HTML中不起作用。
我怎樣才能弄清楚如何防止這種行爲從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}
];
};
});
謝謝,西里爾。完美的作品。我會詳細閱讀文檔。 – lordshark