使用D3js时,与DOM无关的AngularJS数据绑定

时间:2015-01-13 07:22:18

标签: javascript angularjs d3.js angularjs-directive angularjs-scope

我正在使用D3js实现force-layout图。 我已经实现了一个指令,我已经实现了图形。

现在我想在点击每个节点时从后端获取一些数据。 我试图在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>

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

You can use the $scope.$apply() to make sure the DOM is updated. See more here: 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
}).