简体   繁体   中英

AngularJS data-binding with DOM not working while using D3js

I am implementing the force-layout graph using 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.

The ajax call is fine - it is returning the data as expected. The problem is that the data changes are not reflecting on the DOM.

The HTML

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

The AngularJS directive

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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