我正在使用这个很棒的教程来学习如何将 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 绿线(见下面的屏幕截图)。为什么?我没有看到任何会导致此问题的 for
或 while
循环。那么为什么会这样呢?我在上面插入了 console.log 行。它打印了一次About to draw line
。但是它打印了 1
702 次。为什么?这是 plunker
最佳答案
这一行:
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/