javascript - 使用 d3.mouse 事件作为工具提示的面积图的 d3js Angular Directive(指令)

标签 javascript angularjs d3.js angularjs-directive

我有这个http://plnkr.co/edit/fZXbWTGH4qTP4E9LkKyw?p=preview如果您将鼠标悬停在面积图上,它应该显示工具提示,如下所示 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));
    });;

我将 d3js 图表包装在 Angular Directive(指令)中,代码几乎相同,但该事件如何生成此错误“未捕获的类型错误:无法读取 null 的属性“sourceEvent””

最佳答案

问题是您将 d3 javascript 作为服务加载,并且在代码中直接加载它的脚本如下:

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

在您创建 d3service 的代码中,如下所示:

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;
                }
            };
}]);

两者是相同的..:)

2个d3加载冲突是问题的根源,因此你无法在d3中获取鼠标事件。

因此解决方法是删除 d3service 并直接在代码中使用 d3,这样就可以工作了。

工作代码here

关于javascript - 使用 d3.mouse 事件作为工具提示的面积图的 d3js Angular Directive(指令),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34470062/

相关文章:

javascript - 在 Node js 中将字符串转换为 JSON?

javascript - 类型错误 : $ is undefined in jquery

javascript - Angular JS : ng-repeat doesn't work

javascript - d3 路径 d = MNaN,NaNLNaN,NaN

javascript - 类型错误 : Cannot read property 'year' of undefined

javascript - C3条形图-自定义X轴标签

javascript - UI Router 更改 URL 但不更改页面

javascript - 为什么它不改变字体大小?

javascript - Angular : What is the best way to bind to a global event in a directive

javascript - 过滤多个字段的 Angular-UI typeahead 自动完成功能