如何通过HTML到角指令? [英] How to pass HTML to angular directive?

查看:121
本文介绍了如何通过HTML到角指令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个模板的角度指令,但我也不想失去div中的HTML。例如,下面是我想从HTML打电话给我的指令:

I am trying to create an angular directive with a template, but I also don't want to lose the HTML inside of the div. For example, here is how I would like to call my directive from HTML:

<div my-dir>
  <div class="contents-i-want-to-keep"></div>
</div>

然后,有我的指令:

Then, there is my directive:

app.directive('myDir', [ '$compile', function($compile) {
return {
    restrict: 'E',
    link: function(scope, iElement, iAttrs){
        // assigning things from iAttrs to scope goes here
    },
    scope: '@',
    replace: false,
    templateUrl: 'myDir.html'
};
}]);

再有就是myDir.html,在那里我定义一个新的元素:

and then there is myDir.html, where I define a new element:

<div class="example" style="background: blue; height: 30px; width: 30px"></div>

甚至当我设置替换为假的,我失去了内在的内容,我想做对保持DIV - 我的角文档的理解是,这将我的模板后追加。是否有某种方式为preserve这个(可能通过我的链接功能?),这样的结果将是

Even when I set replace to false, I lose the inner contents-i-want-to-keep div - my understanding of the angular docs was that this would be appended after my template. Is there some way to preserve this (possibly through my linking function?) so that the result will be

<div class="example" style="background: blue; height: 30px; width: 30px">
     <div class="contents-i-want-to-keep"></div>
</div>

谢谢!

推荐答案

您需要使用 NG-transclude

您通过设置做到这一点。

You do this by setting

transclude:真正的在你的指令选项,并添加NG-transclude到您的模板:

transclude: true in your directive options, and add ng-transclude to your template:

&LT; D​​IV CLASS =榜样的风格=背景:蓝色;高度:30PX;宽度:30PXNG-transclude&GT;&LT; / DIV&GT;

这plunkr对如何使用NG-transclude与模板,保持原来的DOM元素的例子。

This plunkr has an example on how to use ng-transclude with a template, to keep the original dom element.

http://plnkr.co/edit/efyAiTmcKjnhRZMTlNGf

这篇关于如何通过HTML到角指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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