javascript - 如何在 d3 工具提示的 html 元素中使用 Angularjs 过滤器?

标签 javascript html angularjs d3.js tooltip

我有一个结合了 Angularjs 和 d3js 的网络应用程序。我的一个名为 dailyView 的指令使用在名为 cfg 的服务中定义的函数 drawtooltip() 设置工具提示。指令代码类似如下:

app.directive('dailyView', ['cfg', function (cfg) {

  return {
    restrict: 'E',
    link: function(scope, element, attrs) {
      scope.$watch('daily', function(newVal, oldVal) {
        if (!newVal) return;
        cfg.drawDaily(scope.daily[attrs.bus], element, attrs.bus);
        $('#sortable2').sortable({
            start: scope.dragStart,
            update: scope.dragEnd
        });
        cfg.drawTooltip();
      });
    }
  };
}]);

另一方面,drawTooltip() 函数的定义如下:

app.factory('cfg', ['$window', '$rootScope', '$cookieStore', function($window, $rootScope, $cookieStore){
 function drawTooltip(){

  var tooltip = d3.select(".tooltip");

  d3.selectAll(".myImage")
    .on("mousemove", function(d){
      tooltip.transition().duration(100)
        .style("opacity", .9);
      tooltip.html('<p>{{"' + d.measure + '"|myLocationFilter}}</p>')
        .style("left", (d3.event.pageX + 20)  + "px")
        .style("top", (d3.event.pageY - 110) + "px");    
    })
    .on("mouseout", function(d) {
      tooltip.transition().duration(200)
        .style("opacity", 0);
    });
}

我的 Angular 过滤器应该将 d.measure 字符串转换为根据浏览器语言而变化的描述性文本。问题是我的过滤器未被识别,我的工具提示仅显示以下文本(例如,当绑定(bind)到元素的度量数据是字符串“plug”时:{{“plug”|myLocationFilter}}。

如何将 Angular 过滤器注入(inject) d3js html 元素?

Note: This is a fairly similar question that has not been answered yet.

Edit 1: I've tried using $compile()(scope) in the directive, right after calling cfg.drawtooltip() but the angular filter did not work.

Edit 2: After testing the multiple suggestions offered in the comments, it is clear that the problem lies in the use of the html() method of a d3 selection. Would it be possible to somehow wait until $compile() is processed and then use the outerHTML value of the resulting object?

最佳答案

你需要在输出之前$compile()这个值。

这一行:

 tooltip.html('<p>{{"' + d.measure + '"|myLocationFilter}}</p>')

应该是这样的:

 var compiledElement = $compile('<p>{{"' + d.measure + '"|myLocationFilter}}</p>')($rootScope);
 tooltip.html(compiledElement);

这应该可以正常工作。 我做了一个 fiddle here .您需要注入(inject)和使用 $rootScope 因为您在工厂内部调用它,工厂没有自己的范围。当然还有 $compile,它会为您带来魔力。

通常,对工具提示也使用指令似乎是个好主意。

关于javascript - 如何在 d3 工具提示的 html 元素中使用 Angularjs 过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20482886/

相关文章:

javascript - Angular 计时器 - .stop() 和 .resume() 问题

javascript - 在 Node-webkit 中将 Canvas 保存到磁盘

javascript - 在 react native 应用程序中加载主屏幕之前显示模式

javascript - 在 ExtJS 4 中创建(检查现有)选项卡的新方法

javascript - Javascript 中的日期选择器

html - 带有 AngularJS 的 Jquery UI 对话框

AngularJS - 从嵌入范围访问指令范围

javascript - @font-face 无法在 Chrome 中呈现正确的字体系列

html - 为什么使用此 HTML 代码时右边距没有对齐?

javascript - JS : display selections of a <select> multiple