【问题标题】:AngularJS : How does the HTML compiler arrange the order for compiling?AngularJS:HTML 编译器如何安排编译顺序?
【发布时间】:2013-02-20 19:46:54
【问题描述】:

当一个页面的多个元素有多个指令时,Angular 的 HTML 编译器是如何安排编译顺序的?

假设我有以下标记,其中 alpha、beta 和 gamma 是自定义 Angular 指令,

<html ng-app>
  <alpha><beta></beta></alpha>
  <gamma></gamma>
</html>

编译器对它们的工作顺序是什么?是 alpha => gamma => beta 吗?还是 alpha => beta => gamma?

更复杂一点,考虑 alpha 指令的模板有另一个自定义指令,称为 foo。 foo 什么时候被编译?编译完上述所有指令之后?还是在编译 alpha 之后?

【问题讨论】:

  • 您是否尝试过在指令中添加控制台日志以查看它们的打印顺序?

标签: angularjs angularjs-directive


【解决方案1】:

我在 AngularJS 邮件列表中提出了同样的问题,Peter Bacon Darwin 给出了一个很好的答案,并用 jsfiddle 进行了演示。 Link

【讨论】:

    【解决方案2】:

    关于一个元素上的多个指令

    这是使用指令“优先级”属性处理的。来自文档:Once all directives for a given DOM element have been identified they are sorted by priority and their compile() functions are executed.

    http://docs.angularjs.org/guide/directive

    关于指令编译顺序

    Angular 将遍历 DOM - 即按照元素在 DOM 树中出现的顺序拾取元素。来自文档:Compile: traverse the DOM and collect all of the directives. The result is a linking function.

    http://docs.angularjs.org/guide/compiler

    【讨论】:

    • Alex - 感谢您的回答。指令编译由两部分组成——编译函数和链接函数。您对指令编译顺序所说的只是故事的一半。我在 AngularJS 邮件列表中问了同样的问题,Peter Bacon Darwin 给出了一个很好的答案,用 jsfiddle 进行演示(请参阅接受的答案)。
    【解决方案3】:

    链接和编译函数的顺序在其他答案和https://docs.angularjs.org/api/ng/service/$compile 的 $compile 函数的 Angular 文档中有很好的描述:

    1. 自顶向下编译和预链接(先父,后子)
    2. 反向链接
    3. 同一元素上的指令按其优先级属性处理

    此外: 4. 在指令中使用 templateUrl 选项时,该指令在模板加载之前不会编译,但编译器会继续编译其他指令。这将破坏上述编译/链接顺序。

    【讨论】:

      猜你喜欢
      • 2014-01-09
      • 2012-12-25
      • 1970-01-01
      • 2013-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多