为什么处理AngularJS模型的D3事件在绑定中没有效果?

为什么处理AngularJS模型的D3事件在绑定中没有效果?,angularjs,d3.js,webcola,Angularjs,D3.js,Webcola,考虑以下Angular JS的控制器(1.5.8)。本项目还使用WebCola 3.1.3和d3 3.4.11 当我试图从d3回调处理程序函数中更改$scope的任何属性时,绑定在呈现的HTML中无效 我怎样才能知道如何防止d3出现这种行为,并让双向绑定正常运行 <div ng-controller="MainController"> <h2>{{balls[0].a}}</h2> <button ng-click="foo()">

考虑以下Angular JS的控制器(1.5.8)。本项目还使用WebCola 3.1.3和d3 3.4.11

当我试图从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}
        ];

    };


});

{{balls[0].a}
做吧!
角度.module('nua').controller('MainController',['$scope'],function($scope){
$scope.balls=[];
$scope.onCircleClickHandler=函数(数据、索引){
$scope.balls[index].a=2;
//问题就在这里!
//d3中改变值的每个函数
//任何作用域属性的定义在绑定中无效
//我的同事中没有人试图改变任何
//属性以查看渲染结果
//在这个过程中,它会生效。
//$scope.balls[index].a的值实际上是
//更新为“2”,但的值仍为“1”。
//来自D3的调用似乎阻止了一些影响绑定的事情。
};
$scope.foo=函数(){
$scope.balls[1].d=5;
//这工作正常。
//如果我调用onCircleClickHandler,然后调用foo,
//然后绑定生效,现在具有
//“2”作为innerHTML
};
$scope.init=函数(){
//var mycola=cola.d3adaptor()。。。
//var svg=d3。选择('id')。。。
//var nodes=svg.selectAll('circle')。。。
节点。在('click',函数(数据、索引){
这个.onCircleClickHandler(数据、索引);
}.bind($范围))
$scope.balls=[
{a:1,b:2,c:3},
{d:4,e:5,f:6}
];
};
});

原因是当您更新d3事件中的值时,angular从不知道范围数据已更改,因此需要调用摘要周期

所以应该是这样的:

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

    };

谢谢,西里尔。工作完美。我会读更多关于文档的内容。