本文介绍了如何用 ng-transclude 替换元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以用 ng-transclude 替换元素而不是整个模板元素?

HTML:

<div>{{someData}}</div>

指令:

return {限制:'A',templateUrl:'templates/my-transcluded-directive.html',转置:真,链接:功能(范围,元素,属性){}};

my-transcluded-directive.html:

<div ng-transclude></div><div>我不会被触动的.</div>

我正在寻找的是一种让

{{someData}}

替换

的方法.当前发生的是被嵌入的 HTML 被放置在 inside ng-transclude div 元素.

这可能吗?

解决方案

我认为最好的解决方案可能是创建您自己的 transclude-replace 指令来处理这个问题.但是对于您的示例的快速而肮脏的解决方案,您基本上可以手动将嵌入的结果放置在您想要的位置:

my-transcluded-directive.html:

<span>我将被替换</span><div>我不会被触动的.</div>

指令:

return {限制:'A',templateUrl:'templates/my-transcluded-directive.html',转置:真,链接:功能(范围,元素,属性,ctrl,嵌入){element.find('span').replaceWith(transclude());}};

Is it possible to replace the element with ng-transclude on it rather than the entire template element?

HTML:

<div my-transcluded-directive>
    <div>{{someData}}</div>
</div>

Directive:

return {
    restrict:'A',
    templateUrl:'templates/my-transcluded-directive.html',
    transclude:true,
    link:function(scope,element,attrs)
    {

    }
};

my-transcluded-directive.html:

<div>
    <div ng-transclude></div>
    <div>I will not be touched.</div>
</div>

What I am looking for is a way to have <div>{{someData}}</div> replace <div ng-transclude></div>. What currently happens is the transcluded HTML is placed inside the ng-transclude div element.

Is that possible?

解决方案

I think the best solution would probably be to create your own transclude-replace directive that would handle this. But for a quick and dirty solution to your example you could essentially manually place the result of the transclusion where you want:

my-transcluded-directive.html:

<div>
    <span>I WILL BE REPLACED</span>
    <div>I will not be touched.</div>
</div>

Directive:

return {
    restrict:'A',
    templateUrl:'templates/my-transcluded-directive.html',
    transclude:true,
    link:function(scope,element,attrs,ctrl, transclude)
    {
         element.find('span').replaceWith(transclude());
    }
};

这篇关于如何用 ng-transclude 替换元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 02:38