javascript - 是什么导致在 Angular/D3.js 中重复绘制这条线?

标签 javascript angularjs d3.js

我正在使用这个很棒的教程来学习如何将 D3.js 库与 AngularJS 一起使用:http://briantford.com/blog/angular-d3 .本教程按提供的方式工作(感谢 Brian!)

但我正在努力学习/理解这段代码,以便我可以破解它并绘制我想要的东西。我只是在包含 var bars = layers.selectAll("g.bar") 的行之前添加了以下代码块:

    console.log('Setup');
    var grid = layers.selectAll("g.grid")
        .data(function(d) { return d; })
        .enter().append("g")
        .attr("class", "grid")
        .attr("transform", function(d) {
          console.log("1");
          return "translate(" + x(d) + ",0)";
        });

    console.log('About to draw a line');
    grid.append("line")          // attach a line
      .style("stroke", "green")  // colour the line
      .attr("x1", 100)     // x position of the first end of the line
      .attr("y1", 50)      // y position of the first end of the line
      .attr("x2", 300)     // x position of the second end of the line
      .attr("y2", 150);

我希望这会绘制一条对 Angular 线绿线。相反,它绘制了 700 多条对 Angular 绿线(见下面的屏幕截图)。为什么?我没有看到任何会导致此问题的 forwhile 循环。那么为什么会这样呢?我在上面插入了 console.log 行。它打印了一次About to draw line。但是它打印了 1 702 次。为什么?这是 plunker

enter image description here

最佳答案

这一行:

grid.append("line")  

向网格附加一条线,这意味着您正在使用来自网格的相同数据。因为你的网格是这样的:

var grid = layers.selectAll("g.grid")
        .data(function(d) { return d; })

它使用来自图层的相同数据:

var layers = vis.selectAll("g.layer")
            .data(data)

因此,此数据的长度为 18,但每个数据都有一个包含 39 个元素的数组,因此 18x39=702 即您拥有的行数。

基本上你想将行附加到 vis 而不是网格,否则你将使用相同的数据。

vis.append("line")          // attach a line
          .style("stroke", "green")  // colour the line
          .attr("x1", 100)     // x position of the first end of the line
          .attr("y1", 50)      // y position of the first end of the line
          .attr("x2", 300)     // x position of the second end of the line
          .attr("y2", 150);

更新的 Plnkr:https://plnkr.co/edit/MTQ9pNWL2784jPfRWH5F?p=preview

关于javascript - 是什么导致在 Angular/D3.js 中重复绘制这条线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35784753/

相关文章:

javascript - d3词云-词出界

node.js - Node.js、angular.js 和 MongoDB 入门、建模关系和其他提升技巧

javascript - 使用远程数据自动完成羊驼表单

javascript - 使用 angular2 显示 Bootstrap 警报

javascript - 转换对象数组 - 一些数组和对象操作

javascript - Angular JS $http.get() $scope 问题

angularjs - Angular 2 : Binding to Functions from Component Templates

javascript - 删除 d3 map 中的阿拉斯加和夏威夷

csv - 来自 geojson 或 csv 数据的 map 上的 d3 线和点

javascript - 我如何知道在选择框中选择了哪个对象,或者是否可以将对象绑定(bind)到 KnockoutJS View 模型?