简体   繁体   English

使用D3js时,与AngularJS的DOM数据绑定不起作用

[英]AngularJS data-binding with DOM not working while using D3js

I am implementing the force-layout graph using D3js. 我正在使用D3js实现强制布局图。 I have implemented a directive where I have implemented the graph. 我已经在其中实现了图形的地方实现了一个指令。

Now I wanted to fetch some data from the back-end upon clicking on each node. 现在,我想在单击每个节点时从后端获取一些数据。 I am trying to implement it in an AngularJS controller. 我正在尝试在AngularJS控制器中实现它。

The ajax call is fine - it is returning the data as expected. ajax调用很好-它按预期返回数据。 The problem is that the data changes are not reflecting on the DOM. 问题在于数据更改未反映在DOM上。

The HTML HTML

<div nodes=some-nodes links=some-links force-diagram></div>

The AngularJS directive AngularJS指令

app
.directive('forceDiagram', [function () {
  return {
    replace: true,
    restrict: 'A',
    scope: {},
    controller: 'VisualizeCtrl',
    link: function postLink(scope, iElement, iAttrs) {
        var links = $.parseJSON(iAttrs.links);
        var nodes = $.parseJSON(iAttrs.nodes);
        ...
        ...
        var nodes = svg.selectAll("circle")
                    .data(nodes)
                    .enter()
                    .append("circle")
                    .attr("r", 10)
                    .attr("opacity", 0.5)
                    .on('click', function(d) {
                        // call to a function in the controller
                        return scope.pullData(d);
                    });
        ...
        ...
    };
  }
}])

The AngularJS controller AngularJS控制器

controller('VisualizeCtrl', ['$scope', '$http' function ($scope, $http) {
  $scope.payload = {id:0, text: ''};
  $scope.pullData = function (data) {
        url = 'index.php?r=' + data.node;
        $http({method: 'GET', url: url}).
        success(function(payload) {
            console.log(payload); // this is fine
            $scope.payload = payload;
            console.log($scope.payload) // this is also fine
        }).
        error(function() {
            console.log("error");
        });
    }
  }
}])

But in the following HTML, it is not showing up 但是在以下HTML中,它没有显示

<div ng-controller="VisualizeCtrl">
  <div class="diagram" nodes=some-nodes links=some-links force-diagram></div>
  {{payload}} <!-- this is not showing any changes -->
</div>

Any help is much appreciated. 任何帮助深表感谢。

You can use the $scope.$apply() to make sure the DOM is updated. 您可以使用$ scope。$ apply()来确保DOM已更新。 See more here: http://www.sitepoint.com/understanding-angulars-apply-digest/ 在此处查看更多信息: http : //www.sitepoint.com/understanding-angulars-apply-digest/

The following code should work. 下面的代码应该工作。

success(function(payload) {
        console.log(payload); // this is fine
        $scope.$apply(function() {payload = payload;});
        console.log($scope.payload) // this is also fine
}).

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM