如何编写angularjs指令,取代DOM元素,而无需使用NG-transclude? [英] how to write a directive for angularjs that replaces dom elements without using ng-transclude?

查看:95
本文介绍了如何编写angularjs指令,取代DOM元素,而无需使用NG-transclude?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 < 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>');
        }
    }
});

小提琴

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

这篇关于如何编写angularjs指令,取代DOM元素,而无需使用NG-transclude?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆