d3js angular directive for area chart using d3.mouse event for tooltip

江枫思渺然 提交于 2019-12-11 13:53:45

问题


I have this http://plnkr.co/edit/fZXbWTGH4qTP4E9LkKyw?p=preview where if you hover over the area chart it should have shown the tooltip as the follow up from here roi value in tooltip d3js area chart.

svg.append("path")
    .data([data])
    .attr("class", "area")
    .attr("d", area)
    .on("mouseover", function () {
        tooltip.style("display", null);
    })
    .on("mouseout", function () {
        tooltip.style("display", "none");
    })
    .on("mousemove", function (d) {
        var xPosition = d3.mouse(svg)[0] - 15;
        var yPosition = d3.mouse(svg)[1] - 25;
        tooltip.attr("transform", "translate(" + xPosition + "," + yPosition + ")");
        var x0 = x.invert(d3.mouse(svg)[0]);
        var y0 = y.invert(d3.mouse(svg)[1]);
        tooltip.select("text").text(d3.time.format('%Y/%m/%d')(x0) + " " + Math.round(y0));
    });;

I'm wrapping the d3js chart in a angular directive, code is almost the same but some how this event is generating this error "Uncaught TypeError: Cannot read property 'sourceEvent' of null"


回答1:


The problem is that you loading d3 javascript as a service and in the code you are loading it directly script like this:

  <script src="https://d3js.org/d3.v3.min.js"></script>

And in the code you are creating d3service like this:

angular.module('d3', [])
    .factory('d3Service', ['$document', '$q', '$rootScope',
    function ($document, $q, $rootScope) {
            var d = $q.defer();

            function onScriptLoad() {
                // Load client in the browser
                $rootScope.$apply(function () {
                    d.resolve(window.d3);
                });
            }
            // Create a script tag with d3 as the source
            // and call our onScriptLoad callback when it
            // has been loaded
            var scriptTag = $document[0].createElement('script');
            scriptTag.type = 'text/javascript';
            scriptTag.async = true;
            scriptTag.src = 'https://d3js.org/d3.v3.min.js';
            scriptTag.onreadystatechange = function () {
                if (this.readyState == 'complete') onScriptLoad();
            }
            scriptTag.onload = onScriptLoad;

            var s = $document[0].getElementsByTagName('body')[0];
            s.appendChild(scriptTag);

            return {
                d3: function () {
                    return d.promise;
                }
            };
}]);

Well both are same..:)

The 2 d3 loaded conflicts is the root of the problem and you thus you are not able to get the mouse event in d3.

So the fix is remove d3service and use d3 directly in your code and it will work.

Working code here



来源:https://stackoverflow.com/questions/34470062/d3js-angular-directive-for-area-chart-using-d3-mouse-event-for-tooltip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!