ng-repeat未知数量的嵌套元素

gui*_*mie 8 javascript angularjs angularjs-ng-repeat

我想知道是否有这种问题的简单解决方案.

我有一个对象注释,它可以包含注释,这些注释也可以包含注释......这可以继续进行未知数量的周期.

以下是数据结构的示例:

var comment = {
   text : "",
   comments: [
      { text: "", comments : []},
      { text: "", comments: [
         { text: "", comments : []},
         { text: "", comments : []}
         { text: "", comments : []}
      ]}
   ]
}
Run Code Online (Sandbox Code Playgroud)

让我们说,我会写两个级别的评论:

<div ng-repeat="comment in comments">
   {{comment.text}}
   <div ng-repeat="comment in comments">
      {{comment.text}}
   </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我如何为"n"级嵌套注释实现我的div?

zs2*_*020 10

最简单的方法是创建一个通用的部分,以便您可以使用递归调用和呈现它ng-include.

<div ng-include="'partialComment.html'" ng-model="comments"></div>
Run Code Online (Sandbox Code Playgroud)

这是部分:

<ul>
    <li ng-repeat="c in comments">
      {{c.text}}
      <div ng-switch on="c.comments.length > 0">
        <div ng-switch-when="true">
          <div ng-init="comments = c.comments;" ng-include="'partialComment.html'"></div>  
        </div>
      </div>
    </li>
</ul>
Run Code Online (Sandbox Code Playgroud)

数据模型应该是一个列表var comments = [{ ... }].

我为你创建了一个演示,并希望它有所帮助.

Demo