AngularJS:如何在指令中返回原始元素和新的同级元素

AngularJS: How do I return the original element, with a new sibling element, in a directive?

本文关键字:元素 原始 返回 指令 AngularJS      更新时间:2023-09-26

给定此标记:

<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