3

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

属性附加到父指令模板的指令?

4

1 回答 1

6

假设您有一个指令<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')可以有你想要的任何代码。

这是一个您可能还想阅读的相关问题具有特定类型的通用指令(UI 组件继承)

查看文档中的 transclude 函数以了解如何添加fooin的先前内部元素book

于 2013-05-24T07:32:18.420 回答