How do I use angularjs directives in generated d3 html?

zlog picture zlog · Dec 5, 2013 · Viewed 9.9k times · Source

I'm trying to use the angularjs tooltip directive on my d3 visualisation, so I have something like

var node = svg.selectAll(".node")
    .data(nodes)
    .enter().append("circle")
        .attr("tooltip-append-to-body", true)
        .attr("tooltip", function(d) {
            return d.name;
        })
// ... attributes

However, the tooltips are not showing. Do I need to $compile or something? I've tried wrapping it around $timeout too, but that didn't work.

Answer

jbll picture jbll · Dec 13, 2013

I had a similar problem and yes, solved it with $compile. I'm assuming your d3 code is inside a custom directive. From there you can add your tooltip attributes, remove your custom directive attribute so $compile only runs once, and call $compile:

    myApp.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);

            var node = mySvg.selectAll(".node")
             .data(nodes)
             .enter()
             .append("circle")
             .attr("cx", function(d,i){
                return 20+i*50;
             })
             .attr("cy", 50)
             .attr("r", 10)
             .attr("tooltip-append-to-body", true)
             .attr("tooltip", function(d){
                 return d.name;
             });

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

The $compile service makes sure your element is compiled with the attributes added by your directive.

Here is a working fiddle using the above code. Hope it's what you're looking for!