加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 理解directive定义的transclude选项?

发布时间:2020-12-17 09:21:40 所属栏目:安全 来源:网络整理
导读:我认为这是一个最难的概念,我要理解与angularjs的指令。 从http://docs.angularjs.org/guide/directive的文件说: transclude – compile the content of the element and make it available to the directive. Typically used with ngTransclude. The adva
我认为这是一个最难的概念,我要理解与angularjs的指令。

从http://docs.angularjs.org/guide/directive的文件说:

transclude – compile the content of the element and make it available to the directive. Typically used with ngTransclude. The advantage of transclusion is that the linking function receives a transclusion function which is pre-bound to the correct scope. In a typical setup the widget creates an isolate scope,but the transclusion is not a child,but a sibling of the isolate scope. This makes it possible for the widget to have private state,and the transclusion to be bound to the parent (pre-isolate) scope.

  • true – transclude the content of the directive.
  • ‘element’ – transclude the whole element including any directives defined at lower priority.

它说transclude通常用于ngTransclude。但是从ngTransclude的文档的示例不使用ngTransclude指令。

我想要一些好的例子来帮助我理解这一点。为什么我们需要它?它解决什么?如何使用它?

在元素中考虑一个名为myDirective的指令,该元素包含一些其他内容,假设:
<div my-directive>
    <button>some button</button>
    <a href="#">and a link</a>
</div>

如果myDirective正在使用模板,您会看到< div my-directive>将被您的指令模板替换。所以有:

app.directive('myDirective',function(){
    return{
        template: '<div class="something"> This is my directive content</div>'
    }
});

将导致此渲染:

<div class="something"> This is my directive content</div>

请注意,您的原始元素< div my-directive>将丢失(或更好说,更换)。所以,对这些伙伴说再见:

<button>some button</button>
<a href="#">and a link</a>

那么,如果你想在DOM中保留你的< button> …和< a href> …怎么办?你需要一种叫做互斥的东西。这个概念很简单:包含从一个地方到另一个地方的内容。所以现在你的指令看起来像这样:

app.directive('myDirective',function(){
    return{
        transclude: true,template: '<div class="something" ng-transclude> This is my directive content</div>'
    }
});

这将呈现:

<div class="something"> This is my directive content
    <button>some button</button>
    <a href="#">and a link</a>
</div>.

总之,你在使用指令时想要保留元素的内容时,基本上使用transclude。

我的代码示例是这里http://jsfiddle.net/7LRDS/1/
你也可以从观看:https://egghead.io/lessons/angularjs-transclusion-basics

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读