简体   繁体   English

集成angularjs和d3,简单的数据绑定示例

[英]Integrating angularjs and d3, simple data-binding example

I'm having problems writing a simple directive that updates d3 circle positions using angularjs. 我在编写一个使用angularjs更新d3圆位置的简单指令时遇到了问题。

Here is the example - http://jsfiddle.net/hKxmJ/3/ 这是一个例子 - 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/ 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 我已经设法在google论坛上找到了一些帮助 - 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参数(http://docs.angularjs.org/api/ng.$ro​​otScope.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/ 小提琴在这里: 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(). 关键是跟踪鼠标位置,然后使用反函数更新项目的位置,然后调用范围。$ 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/ 小提琴在这里: http//jsfiddle.net/hKxmJ/7/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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