angularjs中transclusion的主要用途是什么 [英] What is the main use of transclusion in angularjs

查看:26
本文介绍了angularjs中transclusion的主要用途是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在指令中遇到了嵌入,拥有这个概念的目的是什么.据我所知,它封装了一个对象,并且可能有 2 路绑定.但这可以通过在指令的范围属性中使用="来实现.那么指令有什么大不了的?

解决方案

Transclude 允许:

  • 创建包装其他元素的指令.
  • 多次克隆相同的嵌入内容.
  • 在事件发生时重新克隆嵌入的内容.

ngTransclude 和 $transclude

  • 使用 transclude 选项时,元素内容会在编译阶段从 DOM 中删除.
  • linking phase 的第 5 个参数(或 $transclude 内部指令控制器)是一个 $transclude 函数,它允许您克隆嵌入的内容,将其应用到作用域,并在需要时将其重新插入 DOM.
  • Angular.js 有一个针对简单情况的内置指令:ngTransclude

我推荐这些教程:

一些 Angular 内置指令(ng 模块)使用 transclude 选项:

文档

中<块引用>

transclude 选项有什么作用?它使具有此选项的指令的内容可以访问指令之外的范围而不是内部.

实际上,这不太准确,它仅适用于 angular.js 内置指令的默认行为和 $transclude 函数在没有作用域参数的情况下调用时的默认行为.

$transclude 函数允许您应用您需要的任何范围作为可选的第一个参数:

app.directive('example',function(){返回 {转置:真实,模板:

示例

"链接:函数(范围、元素、属性、ctrl、$transclude){$transclude(范围,功能(克隆){element.append(克隆);})}}})

I have recently come across transclusion in directives, what is the purpose of having this concept. As far as I know its encapsulation of an object and have 2-way binding possibly. But this can be possible by using '=' in the scope attribute in directive. So whats the big deal about directive?

解决方案

Transclude allows :

  • To create directives that wrap other elements.
  • To clone the same transcluded contents multiple times.
  • To re-clone the trancluded contents when an event occurs.

ngTransclude and $transclude

  • When using the transclude option, the element contents are being removed from the DOM during the compile phase.
  • The 5th argument of the linking phase ( or $transclude inside directive controllers ) is a $transclude function which allows you to clone the transcluded contents , apply it to a scope and reinsert it to the DOM when you need.
  • Angular.js has a built-in directive for simple cases: ngTransclude

I recommend these tutorials:

Some angular built-in directives (ng module) use the transclude option:

In the docs

What does transclude option do? it makes the contents of a directive with this option have access to the scope outside of the directive rather than inside.

Actually, that's not so accurate, it applies only to the default behavior of angular.js built-in directives and the default behavior of the $transclude function when invoked without scope argument.

The $transclude function allows you to apply any scope you need as an optional first argument:

app.directive('example',function(){
  return {
    transclude: true,
    template: "<div>example</div>"
    link: function (scope, element, attrs, ctrl, $transclude){
      $transclude(scope, function(clone){
        element.append(clone);
      })
    }
  }
})

这篇关于angularjs中transclusion的主要用途是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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