(为什么)在有限的 ng-repeat 中有一个 "calls itself" 的指令会导致无限递归的堆栈溢出?

(Why) does having a directive that "calls itself" in a finite ng-repeat lead to a stack overflow from infinite recursion?

编辑:参见 this plunker for a simplified version of the problem (an sscce)。


以下代码似乎会导致无限递归问题:

statement.directive.html

<textarea></textarea><br />
<button ng-click='statement.newStatement()'>New Statement</button>
<button ng-click='statement.newSubstatement()'>New Substatement</button>
<hr />
<statement
  ng-repeat='statement in statement.curr.sections'
  curr='statement'
  parent='statement.curr'>
</statement>

虽然我不知道为什么。 statement.curr.sections 为零(当我测试它时)。那么该指令不会得到 "instantiated/implemented" 吗?


<p ng-repeat='statement.curr.sections'>x</p>

不会造成任何问题。

将其包装在 ng-if 中并不能解决问题。

<div ng-if='statement.curr.sections > 0'>
  <statement
    ng-repeat='statement in statement.curr.sections'
    curr='statement'
    parent='statement.curr'>
  </statement>
</div>

编辑:这也不起作用(但我意识到我选择了错误的变量名)。

<textarea></textarea><br />
<hr />
<statement
  ng-repeat='item in statementCtrl.curr.sections'>
</statement>

GitHub 上的代码。

我查看了您的 github 代码,但它确实令人困惑。命名肯定让我的大脑陷入困境,所以我首先要澄清一下。

对于指令,您应该使用前缀,以便清楚地表明您引用的是指令:即。 myStatements、elStatement 等等。

对于服务和控制器,使用后缀:StatementService、StatementController。

不明白的地方:

<button ng-click='statement.newStatement()'>New Statement</button>

这里的statement.指的是什么?这什么时候变成 initialized/binded 到视图?编辑:没关系,我看到那是控制器。

好的,你已经得到了指令的模板,引用了指令本身...

嗯,不确定一个指令是否可以有一个子指令本身。当模板试图渲染时,看起来就像无限循环。因为即使下一个 layer/directive 没有数据,它仍然需要 bootstrap 指令及其模板,因此导致它加载下一个指令......并且它永远不会完成。

似乎是一种反模式。用例是什么?你想画分形吗?哈哈

在分形方面,你需要通过一个限制(即当分形变得小到看不见时,就没有画点了)。因此,通过施加一些限制,您可以阻止它无限地尝试绘制。

tl;dr: 即使数据为空,子指令仍然在initialized/rendered.