我有一个结合了 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/