Reputation: 1
I'm new to AngularJS and have written an app which calls an specific API. It gets an object back like this:
posts = [
posts = [...]
users = [...]
]
That's the HTML template:
<div id="{{'post-' + $index}}" ng-repeat="post in posts.posts">
<article>
<h1>{{post.user.username}}</h1>
<span>{{post.date | date: "dd.MM.yy, HH:mm"}}</span>
<p>{{post.content}}</p>
</article>
</div>
I want to show different posts (from the posts object) including the username (which is in the users object). How can I tell Angular that the posts are in the posts object and the proper usernames are in the users object?
Upvotes: 0
Views: 1810
Reputation: 948
If possible, I would suggest you change the structure of the returned JSON object, to something similar to the one below:
posts = [
{
id : "post id",
title: "Post title",
content: "Post content",
date : "post date",
user : {
id: "user id",
name: "user name"
}
},
....
....
]
This should work.
Upvotes: 0
Reputation: 54731
ngRepeat creates a new scope for each entry. That scope will contain $index
for the current offset in the array. Since it's a new scope the variable posts
is now in the $parent
scope.
Assuming posts
and users
contain parallel data and are arrays. You can lookup data in users
using $index
.
<h1>{{$parent.posts.users[$index].username}}</h1>`
Upvotes: 1
Reputation: 64657
Without seeing the structure of the posts
and users
object, it's hard to say exactly, but the general idea is to use the users
object, with the user_id from the post object, so either something like this:
<h1>{{users[post.user.id].username}}</h1>
Or like this:
<h1>{{getUserNameForPost(post)}}</h1>
$scope.getUserNameForPost = function(post) {
//find the user based of the post however you want
user = $scope.users.filter(function(u) { return u.id = post.user });
return user[0].username;
}
Upvotes: 0