简体   繁体   中英

Integrating angularjs and d3, simple data-binding example

I'm having problems writing a simple directive that updates d3 circle positions using angularjs.

Here is the example - http://jsfiddle.net/hKxmJ/3/

This is the model:

 app.controller('AppCtrl', function ($scope) {
   $scope.d = [5, 10, 70, 6, 40, 45, 80, 30, 25];
 });

what the example should do is to be able to update both the circle position and the text next to the input when the number in the input box changes. right now, nothing works except for the initial loading of the directive.

update

http://jsfiddle.net/hKxmJ/5/

I've changed my scope to

app.controller('AppCtrl', function ($scope) {
  $scope.d = [{v: 5}, {v: 10}, {v: 70}, {v: 6}, {v: 40}, {v: 45}, {v: 80}, {v: 30}, {v: 25}];
});

and the text is updating but the watch on the directive is still not updating.

I've managed to find some help on the google forums - https://groups.google.com/forum/?fromgroups=#!topic/angular/NblckkSF6EM

turns out that the scope can be passed an optional objectEquality argument (http://docs.angularjs.org/api/ng.$rootScope.Scope)

objectEquality (optional) – {boolean=} – Compare object for equality rather than for reference.

and now the watch function will work.

 scope.$watch(attr.ghBind, function(value){
    vis.selectAll("circle").data(value)
       .attr("cy", function(d){return d.v;});
    }
 , true);

the fiddle is here: http://jsfiddle.net/hKxmJ/6/

update

I've also managed to generate two-way binding of the data using the mouse to update data-points. The key is to track the mouse position and then to update the item's position using an inverse function, then call scope.$apply(). This is highlighted here:

      .on('drag', function(d, i) {
        var sel = d3.select('.drag'),
          cy = sel.attr('cy');
        sel.attr('cy', parseInt(cy)+d3.event.dy); // Update mouse postion
        d.v = height-Math.round(cy);              // Calculate value using an inverse function
        scope.$apply();                           // Call scope.$apply()
        console.log(d,i,cy);
      })

The fiddle is here: http://jsfiddle.net/hKxmJ/7/

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