AngularJS:如何在指令中返回原始元素和新的同级元素
AngularJS: How do I return the original element, with a new sibling element, in a directive?
给定此标记:
<a href="/" myDirective="Text 1 2 3 Foo">Link</a>
如何使用指令来结束此输出?
<a class="tooltip" style="left:<the left pos of the original element>; top:<the top pos of the original element>;">Text 1 2 3 Foo</a>
<a href="/">Link</a>
谢谢。
EDIT(另一个例子(:
<div myDirective="Text 1 2 3 Foo">
<ul>
<li>Bar</li>
</ul>
</div>
提供:
<a class="tooltip" style="left:<the left pos of the original element>; top:<the top pos of the original element>;">Text 1 2 3 Foo</a>
<div myDirective="Text 1 2 3 Foo">
<ul>
<li>Bar</li>
</ul>
</div>
因此,我本质上想在给定元素之前插入工具提示元素,但在输出时保留给定元素,而不是替换它
.directive('myDirective', function() {
return {
template: "<a class="tooltip" >{{txt}}</a><a href="/">Link</a>",
restrict : 'A',
scope: { txt : "@myDirective" },
replace: true,
link: function(scope,elm,attrs) {
}
}
})
尽管我很确定Angular需要一个元素来替换另一个元素。因此,如果上面的代码不应该工作,请使用这个(用一个跨度包裹它(:
.directive('myDirective', function() {
return {
template: "<span><a class="tooltip" >{{txt}}</a><a href="/">Link</a></span>",
restrict : 'A',
scope: { txt : "@myDirective" },
replace: true,
link: function(scope,elm,attrs) {
}
}
})
干杯,Heinrich
更新:按要求的通用方式:
.directive('myDirective', function() {
return {
template: '<span bind-html-unsafe="{{tmp}}"></span>',
restrict : 'A',
scope: { txt : "@myDirective" },
replace: true,
link: function(scope,elm,attrs) {
scope.tmp = '<'+attrs.tag+' class="tooltip" >{{txt}}</'+attrs.tag+'><a href="/">Link</a>'
}
}
})
你的html:
<legend myDirective="A Text" tag="legend"></legend>
我看到你是新的角度,所以请注意这里创建的新范围。如果需要,您可以使用{{$parent.var}}访问父变量。但您不应该这样做。如果没有太多属性,最好将它们作为属性传递。
最终更新试用@http://plnkr.co/edit/JSOH0cGcYiJIWsVkB8cP
您可以使用$compile来执行自定义模板。
.directive('directive', function($compile) {
return {
restrict : 'A',
scope: { txt : "@directive" },
replace: true,
compile: function compile(elm, attrs, transclude) {
var e = elm;
e.removeAttr("directive");
elm.replaceWith('<span directive="'+attrs.directive+'"><a class="tooltip" href="">{{txt}}</a>'+e[0].outerHTML+'</span>');
elm.append(e);
return {
pre: function preLink(scope, iElement, iAttrs, controller) {
},
post: function postLink(scope, elm, iAttrs, controller) {
$compile(elm.contents())(scope);
}
}
}
}
});
您的HTML模板:
<div directive="{{text}}">
<ul><li>list element</li></ul>
</div>
祝你好运。干杯,Heinrich
相关文章:
- 使用 jQuery 的 .on 函数如何获取事件的原始元素
- JQuery:使用clone()生成的元素不采用原始的事件属性
- 如何显示替换为后的原始元素
- jQuery's clone()函数扰乱了原始元素'的属性
- 将jQuery$(this)转换为原始元素
- React警告:ReactMount:根元素已从其原始容器中删除.新容器:[object HTMLDivElement]
- 正在将DOM元素转换为原始HTML字符串
- 移动|克隆元素并从原始位置移除
- 滚动后,检测元素何时返回到原始位置
- 从第三方原始javascript控制Angular JS元素
- html5可拖动隐藏原始元素
- AngularJS指令,该指令使用模板中的原始元素类型
- 使用 .on 获取原始元素
- 如何获取固定元素的“原始”偏移量().top
- 我可以在 ReactJS 中排除原始元素的子元素吗?
- 独立于原始元素复制元素
- 确定元素是否由 JS 添加,还是原始 HTML 文档 *OR* 检测脚本何时通过 InnerHTML 更新节点
- 如何从事件中获取原始元素
- 获取聚合物元素的原始 HTML 代码
- 旋转元素而不返回到原始状态