如何将 HTML 传递给 angular 指令? [英] How to pass HTML to angular directive?

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

问题描述

我正在尝试使用模板创建一个 angular 指令,但我也不想丢失 div 中的 HTML.例如,下面是我想从 HTML 调用我的指令的方式:

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

然后是我的指令:

app.directive('myDir', [ '$compile', function($compile) {返回 {限制:'E',链接:功能(范围,iElement,iAttrs){//将 iAttrs 中的东西分配给作用域},范围: '@',替换:假,templateUrl: 'myDir.html'};}]);

然后是 myDir.html,我在其中定义了一个新元素:

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

即使我将 replace 设置为 false,我也会丢失内部 content-i-want-to-keep div - 我对 angular 文档的理解是这将附加在我的模板之后.有没有办法保留它(可能通过我的链接功能?),以便结果是

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

谢谢!

解决方案

你需要使用 ng-transclude,在您的指令选项中添加 transclude: true,并将 ng-transclude 添加到您的模板中:

</div>`

这个 plunkr 有一个关于如何将 ng-transclude 与模板一起使用的示例,以保留原始 dom 元素.

http://plnkr.co/edit/efyAiTmcKjnhRZMTlNGf

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

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

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

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>

Thanks!

解决方案

You'll need to use ng-transclude, add transclude: true in your directive options, and add ng-transclude to your template:

<div class="example" style="…" ng-transclude></div>`

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 传递给 angular 指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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