问题描述
我在互联网上搜索了很长时间,没有找到直接的答案.我的问题很简单,我想在我的标记中有这样的东西:
I've searched the internet long and hard and found no straight answer. My question is simple, I want to have something like this in my markup:
<div my-tooltip-template="'mytt.tpl.html'" my-tooltip-scope="myDataItem">Some text...</div>
其中 myDataItem
是一个范围变量,它包含我的数据对象,以及一个可能如下所示的模板:
Where myDataItem
is a scope variable which contains my data object, and with a template which might look like:
<h1>{{dataItem.title}}</h1>
<span>{{dataItem.description}}</span>
并且我希望使用包含 myDataItem
作为 dataItem
的范围编译该模板并显示为工具提示.据我通过试验 ui-bootstrap
tooltip
模块得知,将 html 注入工具提示的方法是使用指令 tooltip-html-unsafe
但注入的 html 没有被编译,即不计算角度表达式,不扩展指令等.
And I want to have that template compiled with the a scope which contains myDataItem
as dataItem
and displayed as a tooltip. As far as I could tell by experimenting with ui-bootstrap
tooltip
module, the way to inject html into a tooltip is by using the directive tooltip-html-unsafe
but the html injected doesn't get compiled, i.e., angular expressions are not evaluated, directives are not expanded, etc.
我该如何为此创建指令?我想要一个精益的结果,我不想包含 jQuery 或任何其他库,只是 AngularJS 和 ui-bootstrap.
How do I go about creating a directive for this? I want a lean result, I don't want to have to include jQuery or any other library, just AngularJS and ui-bootstrap.
非常感谢!
推荐答案
这里是如何根据您的要求创建工具提示的蓝图(或使用 ui-bootstrap 的工具提示修改/合并).
Here're the blueprints of how you could create a tooltip according to your requirements (or modify/encorporate this with ui-bootstrap's tooltip).
app.directive("myTooltipTemplate", function($compile){
var contentContainer;
return {
restrict: "A",
scope: {
myTooltipScope: "="
},
link: function(scope, element, attrs, ctrl, linker){
var templateUrl = attrs.myTooltipTemplate;
element.append("<div ng-include='\"" + templateUrl + "\"'></div>");
var toolTipScope = scope.$new(true);
angular.extend(toolTipScope, scope.myTooltipScope);
$compile(element.contents())(toolTipScope);
}
};
});
当然,这没有任何实际的工具提示功能,例如弹出窗口、放置等... - 它只是将编译后的模板附加到该指令适用的任何元素上.
This, of course, doesn't have any of the actual tooltip functionality, like popup, placement, etc... - it just appends the compiled template to whatever the element that this directive applies to.
更改了 plunker 更接近工具提示的行为;
Changed plunker with closer-to-tooltip behavior;
这篇关于如何使用编译模板创建 AngularJS 工具提示指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!