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

How can I use an Angularjs filter within the html element of a d3 tooltip?

本文关键字:Angularjs 过滤器 元素 html d3 工具提示      更新时间:2024-06-14

我有一个结合了Angularjs和d3js的web应用程序。我的一个指令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);
    });
}

我的角度过滤器应该将d.measure字符串转换为描述性文本,该文本会根据浏览器语言进行更改。问题是我的过滤器无法识别,我的工具提示只显示以下文本(例如,当绑定到元素的度量值数据是字符串"plug"时:{{"plug"| myLocationFilter}}。

如何将我的角度过滤器注入d3js-html元素?

注:这是一个相当相似的问题,但尚未得到回答。

编辑1:在调用cfg.drawtooltip()之后,我尝试在指令中使用$compile()(scope),但角度过滤器不起作用。

编辑2:在测试了评论中提供的多个建议后,很明显,问题在于使用了d3选择的html()方法。是否可以以某种方式等待$compile()被处理,然后使用结果对象的outerHTML值?

在输出值之前,您需要$compile()

此行:

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

应该是这样的:

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

这应该很有效。我在这里做了一把小小提琴。您需要注入并使用$rootScope,因为您在工厂内部调用它,而工厂没有自己的作用域。当然还有$compile,它对你有魔力。

一般来说,将指令也用于工具提示似乎是个好主意。