0

I am using the d3.js library inside an angular 1.x controller. My d3.js library creates a click event on a div and when the div is clicked, it updates something on the angular controller's scope.

The problem is, when I change the scope ($scope.test = "a test"), the modification is not reported into the template.

However, if, inside that d3.js click event, I do a $scope.$apply (as suggested by this related topic: Angular + D3 - Get scope values to show in template from click event), the dom is updated and everything works fine.

Since the use of scope is discouraged, is there another solution that will make the changes appear in my template?

Here is my code:

<!DOCTYPE html>
<html lang="en">
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.1/d3.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>
</head>
<body>
  <div  ng-app="app" >
    <div id="main" ng-controller="main">    
      test is {{test}}
      <div id="graph">
        hello  
      </div>
    </div>
  </div> 
</body>
<script type="text/javascript">
  var app = angular.module('app',[]);
  app.controller('main', function($scope){

    $scope.force_refresh = function(){}

    d3.selectAll("#graph").on("click", function() {
      $scope.test = "a test";
      //////////I would like to avoid this/////////////
      $scope.$apply();             ////////////////////
      //////////I would like to avoid this/////////////
    });
  });

</script>
</html>
Community
  • 1
  • 1
Filip Novotny
  • 397
  • 1
  • 4
  • 9

0 Answers0