使用指令作为属性时的转换

时间:2017-01-20 10:38:51

标签: angularjs angular-directive

我在使用angular管理指令作为属性的方式时遇到了麻烦。

我有一个使用transclusions的元素指令:

<xx-button>Button!</xx-button>

我有一个指令,通过添加一些其他指令来改变元素的内容:

<xx-button xx-modifying-directive>Button!</xx-button>

这将被修改为:

<xx-button some-other-directives>
  <button>Button!</button>
</xx-button>

当我在xx-modifying-directive指令的链接函数中编译元素的内容时,出现以下错误:

  

在模板中非法使用ngTransclude指令!没有找到需要转换的父指令。元素:

您可以在JSFiddle中更清楚地看到问题。

阅读doc或ngRepeat的源代码我不知道如何解决这个问题。

注意:我需要在xx-modifying-directive中编译我的元素,因为这个指令添加了需要编译的其他指令(在我的实际情况中,我正在添加像hm-pan这样的锤子处理程序。)

更新

仔细观察,问题来自于(ngTransclude指令)[https://github.com/angular/angular.js/blob/2a156c2d7ec825ff184480de9aac4b0d7fbd5275/src/ng/directive/ngTransclude.js#L59]未通过transclude函数这一事实。

仍然不知道为什么,因为它实际上有一个激活了transclude的祖先(xx-button)。

1 个答案:

答案 0 :(得分:1)

必须向$transclude提供$compile功能。它被传递给link函数。

link: function(scope, elem, attrs, $transclude) {
  [...]
  if ($transclude) { // It can be undefined if not content is provided
    $compile(element, $transclude)(scope);
  }
  [...]
}

如果您想深入了解转换业务,请按照link

进行操作
相关问题