首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么处理D3模型的AngularJS事件在绑定中没有效果?

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

Stack Overflow用户
提问于 2016-12-16 19:35:15
回答 1查看 81关注 0票数 2

考虑以下角JS控制器(1.5.8)。该项目还使用了WebCola 3.1.3和d3 3.4.11。

当我试图在$scope回调处理程序函数中更改d3的任何属性时,绑定在呈现的HTML中不起任何作用。

我如何才能知道如何防止这种行为从d3和让双向绑定流正常?

代码语言:javascript
复制
<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}
        ];

    };


});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-17 10:21:26

原因是当您从d3事件更新值时,角永远不会知道范围数据已经更改,因此需要调用摘要周期。

所以应该是这样:

代码语言:javascript
复制
 $scope.onCircleClickHandler = function (data, index) {
        //this will notify angular that the scope value has changed.
        $scope.$apply(function () {
            $scope.balls[index].a = 2;
        });

    };
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41191327

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档