如何编写angularjs指令,取代DOM元素,而无需使用NG-transclude?指令、元素、angularjs、DOM

2023-09-13 05:14:29 作者:过客已经够多了

我希望写一个指令,基本上这个转换:

 < G:文本>你好< / G:文本>至< SVG类=GX-文本><文字和GT;你好< /文本>< / SVG> 

这样在DOM中,< G:文本> 元素已经由&LT被完全取代; SVG> 元素

我不想用NG-transclude,因为我发现,它增加了很多其他的元素到DOM。

解决方案

  VAR应用= angular.module('应用',[]);app.directive('gText',函数(){    返回{        限制:'E',        编译:功能(tElement,ATTRS){            tElement.replaceWith('< SVG类=GX-文本><文字和GT;'                + tElement.text()+'< /文本>< / SVG>');        }    }}); 

小提琴

使用AngularJS开发我们下一款Web应用的七个理由

I wish to write a directive that basically transforms this:

<g:text>Hello There</g:text>

to

<svg class="gx-text"><text>Hello There</text></svg>

so that in the dom, the <g:text> element has been completely replaced by the <svg> element

I don't want to use ng-transclude as I found that it added a bunch of other elements to the dom.

解决方案

var app = angular.module('app', []);
app.directive('gText', function() {
    return {
        restrict: 'E',
        compile: function(tElement, attrs) {
            tElement.replaceWith('<svg class="gx-text"><text>'
                + tElement.text() + '</text></svg>');
        }
    }
});

​Fiddle