【问题标题】:how to manually compile templates twice or more如何手动编译模板两次或更多次
【发布时间】:2013-05-23 19:27:54
【问题描述】:

我想先编译一个角度指令来附加属性,然后再将代码编译为其他指令。无论如何我可以使用 compile: pre post 或其他东西来编译这个

属性附加 至 指示 至 父指令模板?

【问题讨论】:

    标签: angularjs hyperlink compilation directive


    【解决方案1】:

    假设您有一个指令<foo></foo> (restrict: 'E')。您想要动态添加属性(~ 修改原始 DOM,而不是模板),这应该在指令的 $compile 步骤中完成。添加属性后,要让 angularjs 意识到是否有可以触发的新指令,您必须编译新元素。例如,这就是 ng-include 所做的。它包含 DOM 中的元素并编译它们以便可以使用新的指令。

    指令foo:

    compile: function ($tElement, $tAttrs) {
      var el = $tElement[0];
      el.setAttribute('bar', 'newFancyValue');
      return function (scope, element, attrs) {
         // you can even append html elements here, for example the template
         element.append("<book></book>");
         $compile(element)(scope);
      };
    }
    

    指令bar(带有restrict: 'A')可以有任何你想要的代码。

    这是一个您可能也想阅读的相关问题A general directive with a specific type (UI components inheritance)

    查看文档中的 transclude 函数,了解如何在 book 中添加 foo 之前的内部元素

    【讨论】:

    • 如果你的 'foo' 指令是限制 'A' 怎么办?在这种情况下,编译循环似乎永远......
    • 是的,可能是因为编译后,Angular 再次找到触发指令的属性,这使得它一次又一次地编译它。我想您可以删除编译函数中的属性并仅在该属性存在时才返回链接函数。类似问题stackoverflow.com/questions/15929386/…
    • 知道为什么编译$tElement的第一个参数是一个数组而不是一个元素,因此需要var el = $tElement[0];。大多数示例将其视为单个对象,但与 OP 一样,我得到一个数组。
    猜你喜欢
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    • 2021-04-10
    • 2015-11-23
    • 2013-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多