AngularJs directive 'transclude' option 详解

 

transclude好像不是一个英语单词,有道词典里没有,百度翻译的意思是嵌入。

transclude在angularjs的自定义的derective中是比较常见的一个东西,所有有必要要了解它。

我们首先看下官方api对ng-transclude的解释:

Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion. 
Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.

官方例子:

<div ng-controller="Ctrl">
      <input ng-model="title"><br>
      <textarea ng-model="text"></textarea> <br/>
      <pane title="{{title}}">{{text}}</pane>
</div>

pane是一个自定义derective,标签里还有一个表达式,这个指令的目的是显示 input中输入的title,和textarea中输入的text,当然是按照一定的dom结构显示。看下pane是如何实现:

app.directive('pane', function() {
    return {
      restrict: 'E',
      transclude: true,
      scope: { title:'@' },
      template:
                '<div style="border: 1px solid black;">' +
                    '<div style="{{title}}</div>' +
                    '<div ng-transclude></div>' +
                '</div>'
    };
});

首先是我们想把 <pane title="{{title}}">{{text}}</pane> 中{{title}}{{text}}变量的内容封装到我们的dom结构中,{{title}} 可以通过结构scope: { title:'@' }取得,但是我们想要保留 <pane></pane> 标签里的东西(有可能会是很多的表达式和dom结构),那就需要今天的主角 transclude了。

这个例子的结果生成的dom结构是这样的:

<div style="border: 1px solid black;">
    <div style="background-color: gray">我是标题</div>
    我是内容
</div>

有个这样结果我想你就看明白了。原来模板中的 <div ng-transclude></div> 最后会被<pane></pane>标签里的表达式内容所替换。这是就是transclude的用途。

转载于:https://www.cnblogs.com/xbingxin/p/3941877.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值