什么时候在指令设置的 compilation/linking 过程中发生嵌入?

When does transclusion take place in the compilation/linking process of a directive's setup?

我正在编写一个使用嵌入的自定义指令。我需要在嵌入发生后对嵌入的 DOM 内容进行修改....我想在 post-link 或控制器中或.. . link...?我不知道嵌入发生在那些事情发生的顺序中,所以我不知道如何确保我的 JS 在嵌入发生后执行。

嵌入发生在编译阶段。 Angular 的 $compile 服务超越 DOM,如果指令启用了嵌入,Angular 提取元素的内容(如果 transclude: true,或元素本身 - 对于 transclude: 'element'),编译它们,并使编译后的内容在嵌入函数中可用,绑定到嵌入范围。

因此,执行顺序为:

  1. Angular 嵌入内容并编译它:compile 函数 嵌入的内容 指令执行
  2. 指令的
  3. compile函数执行-returnspre-和post-link函数
  4. controller 函数 的指令 执行
  5. pre-link 函数 的指令 执行
  6. post-link 指令 的函数 执行。

您可以决定在post-link函数中执行transclude函数。只要你这样做,

  1. controllerpre- 和 post-link 函数 包含的内容 指令执行

transclude 函数在步骤 #3-#5 可用,调用时,它会向 cloneAttachFn 提供嵌入元素的新副本,您将其作为参数提供给transclude 函数:

link: function(scope, element, attrs, ctrls, transclude){
    transclude(scope, function cloneAttachFn(clone){
      // you can do DOM manipulation of the clone instance here
    });
}

请注意,cloneAttachFn 中的 DOM 操作将应用于嵌入的 DOM 的实例 - 而不是预编译的 DOM 模板。