簡體   English   中英

使用D3js時,與AngularJS的DOM數據綁定不起作用

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

我正在使用D3js實現強制布局圖。 我已經在其中實現了圖形的地方實現了一個指令。

現在,我想在單擊每個節點時從后端獲取一些數據。 我正在嘗試在AngularJS控制器中實現它。

ajax調用很好-它按預期返回數據。 問題在於數據更改未反映在DOM上。

HTML

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

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);
                    });
        ...
        ...
    };
  }
}])

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");
        });
    }
  }
}])

但是在以下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>

任何幫助深表感謝。

您可以使用$ scope。$ apply()來確保DOM已更新。 在此處查看更多信息: http : //www.sitepoint.com/understanding-angulars-apply-digest/

下面的代碼應該工作。

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