【问题标题】:AngularJS D3. How to append anything to existing graph (draw over it)?AngularJS D3。如何将任何内容附加到现有图表(绘制它)?
【发布时间】:2015-10-30 03:33:21
【问题描述】:

网上所有的例子似乎都是用 using

    d3.select("body").append("div") etc. 

如何将一些东西附加到已经存在的图形上?我假设这将是这样的指令?

.controller(....)
.directive('myNodes', ['$compile', function ($compile) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var nodes = [{"name": "foo"}, {"name": "bar"}];
            var mySvg = d3.select(element[0])
            .append("svg")
            .attr("width", 100)
            .attr("height", 100);

            mySvg.append("line")
            .style("stroke", "green")
            .attr("x1", 1)
            .attr("y1", 1)
            .attr("x2", 40)
            .attr("y2", 50);

            element.removeAttr("my-nodes");
            $compile(element)(scope);
        }
      };
  }]);

但我发现的所有示例都添加了另一个 svg,我无法选择现有的一个

小提琴 http://jsfiddle.net/shuxerezad/8kzesguo/

【问题讨论】:

    标签: javascript angularjs d3.js svg


    【解决方案1】:

    为了在已经绘制的 svg 上附加一条线

    您将 svg 附加/创建到元素的情况:

    var mySvg = d3.select(element[0])
                .append("svg")
                .attr("width", 100)
                .attr("height", 100);
    

    要附加到已经绘制的 svg 上:

     var mySvg = d3.select(element[0]).select("svg");//get the svg already drawn there
    

    现在,由于您使用的是角度指令,因此上面的 mySVG 可能会为空,原因是 nvd3 稍后绘制图形,而绘制线的时间是 d3.select(element[0]).select(" svg") 将没有 svg。

    因此,您需要在延迟后触发指令链接函数,以便绘制 svg 并准备好图形。

    link: function (scope, element, attrs) {
                var doRender = function () {
                    var nodes = [{
                        "name": "foo"
                    }, {
                        "name": "bar"
                    }];
                    var mySvg = d3.select(element[0]).select("svg");
    
                    mySvg.append("line")
                        .style("stroke", "green")
                        .attr("x1", 1)
                        .attr("y1", 1)
                        .attr("x2", 400)
                        .attr("y2", 50);
                    // Make sure that $compile doesn't recompile
                    // the directive and remove the d3 nodes
                    element.removeAttr("my-nodes");
                    $compile(element)(scope);
                }
                setTimeout(doRender, 3000);//so that the line is drawn when the svg is present...execute doRender after 3 secs
            }
    

    完整的工作代码here

    希望这会有所帮助!

    【讨论】:

    • 谢谢!有时有助于理解基础知识)
    猜你喜欢
    • 2023-03-30
    • 2014-06-14
    • 2012-10-27
    • 2017-11-25
    • 2017-03-24
    • 1970-01-01
    • 2016-07-28
    • 2012-07-25
    • 2021-02-13
    相关资源
    最近更新 更多