Even Simpler Tooltip with D3.js and AngularJS

Using $compile to apply an angularjs tooltip directive to a d3 visualization.

by Gabriel Z

HTML

<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.6.0/ui-bootstrap-tpls.js"></script>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<div ng-app="myApp" ng-controller="myCtrl">
    <div my-nodes></div>
</div>

JavaScript

var myApp = angular.module('myApp', ['ui.bootstrap']);

myApp.controller('myCtrl', ['$scope', function($scope){
    }]);

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", 200)
                      .attr("height", 100);
                         
                var node = mySvg.selectAll(".node")
                 .data(nodes)
                 .enter()
                 .append("circle")
                .attr("cx", function(d,i){
                    return 50+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);
                }
            };
        }]);