2

I have the following json object:

"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" }
    ] }
]

As you can see, each comment could have a child comment so it could literally go on forever. I am trying to display all of them but I can't figure out how I would do this.

This is all I have so far (obviously this only gets the first child in each comment):

<div ng-repeat="comment in comments">
    {{ comment.comment}}
    <div ng-repeat="c in comments.child">
        {{c.comment}}
    </div>
</div>
bryan
  • 8,879
  • 18
  • 83
  • 166
  • I'd look for "recursion angular" on Google. Found this first result http://benfoster.io/blog/angularjs-recursive-templates – elclanrs Aug 26 '15 at 17:44

3 Answers3

2

You could create your own directive that you can call recursively for your case

Markup

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

Directive

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>
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
0

What you need is a tree view.

A good way is to print them not all at once, but only the first order comments, and add a button for loading the next ones (subcomments).

You can use a directive to do this, and encapsulate all the comments.

There is a good stackoverflow question for this.

Community
  • 1
  • 1
Guilherme
  • 1,980
  • 22
  • 23
0

You could create a directive that references itself:

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>
Vito
  • 96
  • 6