vbotio vbotio - 4 months ago 26
JSON Question

How to use ng-repeat in a nested json in an ionic project

I'm trying to use

ng-repeat
in a nested json object.

{
"title": "Important message 01",
"img": "any url image here",
"authorPhoto": "http://lorempixel.com/40/40/people/4/",
"author": "John Doe",
"datePosted": "1 day ago",
"thumbsUp": "245",
"thumbsDown": "200",
"commentsNum": "123",
"id": "1",
"comments": [
"comment",
{
"authorCommentPhoto": "http://lorempixel.com/40/40/people/5/",
"author": "Jimmy doe",
"text": "useless commment",
"dateCommented": "01/08/2016"
}
]
}


I can list the top level json (title, img, etc...), but I do know how to list the comments part

<ion-item ng-repeat="card in cards" href="#/app/playlists/{{card.id}}" class="card-wrapper">
<div class="card" style="background: url({{card.img}}); background-size:100%;">
<div class="inner-wrapper">
<img ng-src="{{card.authorPhoto}}" alt="Author profile photo">
<p class="author">{{card.author}} <br>
{{card.datePosted}}
</p>
<p class="essay">{{card.title}}</p>
<div class="footWrapper">
<div class="thumbsUp"><i class="icon ion-arrow-up-c"></i>{{card.thumbsUp}}</div>
<div class="comments">{{card.commentsNum}}</div>
<div class="thumbsDown"><i class="icon ion-arrow-down-c"></i>{{card.thumbsDown}}</div>
</div>
</div>
</div>
<div class="commentsWrapper">
<div class="head">
<img class="profilePhoto" src="http://tilomitra.com/wp-content/uploads/2014/08/avatar-cartoon.png" alt="avatar photo">
<input type="text" placeholder="Write a comment...">
</div>
<div class="commentsContainer">
<ul>
<li ng-repeat="comment in cards.comments">
{{comment.authorCommentPhoto}} <br>
{{comment.author}} <br>
{{comment.text}} <br>
{{comment.dateCommented}}
</li>
</ul>
</div>
</div>
</ion-item>


How can I solve this ?

Answer

The comments array has a string and an object. Remove the string "comments" and just use an array of objects. Then use ng-repeat="comment in card.comments"

{
  "comments":[
     {
                "authorCommentPhoto": "http://lorempixel.com/40/40/people/5/",
                "author": "Jimmy doe",
                "text": "useless commment 1",
                "dateCommented": "01/08/2016"
     },
     {
                "authorCommentPhoto": "http://lorempixel.com/40/40/people/5/",
                "author": "Jimmy doe",
                "text": "useless commment 2",
                "dateCommented": "01/09/2016"
     }
  ]
}