angularjs - 了解指令定义的 transinclude 选项?

标签 angularjs angularjs-directive

我认为这是我用 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 文档中的示例根本不使用 ngTransinclude 指令。

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

最佳答案

考虑一个元素中名为 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>

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

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

这将呈现:

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

总之,当您想在使用指令时保留元素的内容时,基本上可以使用 transclude。

我的代码示例是 here 。 您还可以从观看 this 中受益.

关于angularjs - 了解指令定义的 transinclude 选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15296284/

相关文章:

javascript - ng-class 允许赋值运算符。这是一个错误还是功能?

javascript - 如何从 Controller 中访问 app.js 中的 .state() 以使用 ROUTER 中的项目

javascript - 如何让 ng-disabled 检查 ng-repeat 中的项目值(使用 AngularJS)

javascript - AngularJS 自定义表单验证指令在我的模式中不起作用

angularjs - ui.bootstrap.datepicker 清除按钮事件

javascript - 如何从 Angular JS 中的 get 请求获取输入字段中的数据?

javascript - AngularJS:在JSP中获取$http.post数据

angularjs - 从 Controller 关闭 Angular 引导模式窗口

javascript - Angular 自定义可折叠指令在包裹 ng-repeat 内容时失败

javascript - 作用域函数未接收回调参数