无限的,永无止境的,嵌套的ng-repeat

时间:2015-08-26 17:43:07

标签: javascript angularjs angularjs-ng-repeat

我有以下json对象:

"comments": [
    {"username": "test", "comment": "This is a comment",
    "child": [
        {"username": "chriscool", "comment": "I replied to the above comment",
        "child": [
            {"username": "Anotherperson", "comment": "But what if I replied again",
            "child": [
                {"username": "ralphy", "comment": "And again?!" }
            ] }
        ] },
        {"username": "ralphy", "comment": "I also replied" }
    ] }
]

正如您所看到的,每个评论都可能有child评论,因此它可以永远继续下去。我试图展示所有这些,但我无法弄清楚我将如何做到这一点。

这是我到目前为止所有这一切(显然这只是每个评论中的第一个孩子):

<div ng-repeat="comment in comments">
    {{ comment.comment}}
    <div ng-repeat="c in comments.child">
        {{c.comment}}
    </div>
</div>

3 个答案:

答案 0 :(得分:2)

你可以创建自己的指令,你可以递归调用你的案例

<强>标记

<div my-recursive-dir="comments"><div>

<强>指令

app.directive('myRecursiveDir', function(){
  return {
     templateUrl: 'Recursive.html',
     scope: {
        comments: '=',
     },
     replace: true
  };
});

<强> Recursive.html

<div ng-repeat="c in comments.child">
    {{c.comment}}
    <div ng-if="c.child" my-recursive-dir="c"><div>
</div>

答案 1 :(得分:0)

您需要的是tree view

一个好方法是不是一次打印它们,而只打印第一个顺序注释,并添加一个按钮来加载下一个(子注释)。

您可以使用指令执行此操作,并封装所有注释。

有一个很好的stackoverflow question for this

答案 2 :(得分:0)

您可以创建一个引用自身的指令:

angular.directive('myDirective', function() {
  return {
    scope: {
      comment: "="
    },
    templateUrl: "myDirective.html"
  }
})

<script type="text/ng-template" id="myDirective.html">
  {{ comment.comment }}
  <div ng-repeat="child in comment.child">
    <my-directive comment="child"></my-directive>
  </div>
</script>

<my-directive ng-repeat="comment in comments" comment="comment"></my-directive>