最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to write a directive for angularjs that replaces the dom element but keeps bindings - Stack Overflow

programmeradmin2浏览0评论

following on from this question: how to write a directive for angularjs that replaces dom elements without using ng-transclude?

I wish to write a directive that changes the dom element but then retains all the attributes and bindings.

<g:text x={{myX}} y={{myY}} font-size=10>Hello There</g:text>

to

<text x={{myX}} y={{myY}} font-size=10>Hello There</text>

thanks in advance!

following on from this question: how to write a directive for angularjs that replaces dom elements without using ng-transclude?

I wish to write a directive that changes the dom element but then retains all the attributes and bindings.

<g:text x={{myX}} y={{myY}} font-size=10>Hello There</g:text>

to

<text x={{myX}} y={{myY}} font-size=10>Hello There</text>

thanks in advance!

Share Improve this question edited May 23, 2017 at 12:08 CommunityBot 11 silver badge asked Dec 14, 2012 at 12:45 zcaudatezcaudate 14.3k7 gold badges68 silver badges134 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

To the best of my knowledge, Angular will port attributes to the new element automatically. No need to iterate over them all yourself.

In your case, you would also need to transclude the content if you want to keep it.

app.directive('myText', function() {
    return {
        replace: true,
        template: '<text ng-transclude></text>'
    }
});

This is from the top of my memory, but I believe something similar to this would do the trick. Every attribute of the original element will be ported to the new element, and the element's content will be transcluded too. Binds preserved and all.

Use the same logic and copy the attributes during the pile:

 app.directive('gText', function() {
    return {
        restrict: 'E',
        pile: function(tElement, tAttrs) {
            var attrs = tElement[0].attributes;
            tElement.replaceWith('<text>' + tElement.text() + '</text>');            
            for (var i=0; i < attrs.length; i++) {
                tElement.attr(attrs.item(i).nodeName, attrs.item(i).nodeValue);               
            }
        }
    }
});

fiddle: http://jsfiddle/YWfSF/

(In response to Jason Swett request for an update)

this works in Angular 1.4.9 (and prob earlier too)

return {
      restrict: 'E', // optional
      replace: true, // optional
      template: '<span data-ng-transclude></span>',
      transclude: true,
      link: function (scope, el, attrs) .........
}

A great article on this is at ...

https://www.accelebrate./blog/angularjs-transclusion-part-1/

发布评论

评论列表(0)

  1. 暂无评论