0

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?

2
  • What does a post look like? Are the posts and user arrays mapped 1-to-1? Commented Jul 14, 2014 at 20:26
  • Looks to me like the data you are returning should be formatted better. The way it is now you assume there is a 1 to 1 relationship. if that is the case then you should be able to put them both in the same object. Commented Jul 14, 2014 at 20:26

3 Answers 3

1

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>`
Sign up to request clarification or add additional context in comments.

Comments

0

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;
}

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.