AngularJS ng-repeat与不同的对象

时间:2014-07-14 20:24:07

标签: arrays json angularjs object

我是AngularJS的新手,并编写了一个调用特定API的应用。它得到一个像这样的对象:

posts = [
    posts = [...]
    users = [...]
]

这是HTML模板:

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

我想显示不同的帖子(来自posts对象),包括用户名(在users对象中)。如何告诉Angular帖子在posts对象中,而正确的用户名在users对象中?

3 个答案:

答案 0 :(得分:1)

ngRepeat为每个条目创建一个新范围。该范围将包含$index,用于数组中的当前偏移量。由于它是一个新的范围,变量posts现在位于$parent范围内。

假设postsusers包含并行数据并且是数组。您可以使用users$index中查找数据。

<h1>{{$parent.posts.users[$index].username}}</h1>`

答案 1 :(得分:0)

如果没有看到postsusers对象的结构,很难准确说出,但一般的想法是使用带有user_id的users对象来自post对象,所以要么像这样:

<h1>{{users[post.user.id].username}}</h1>

或者像这样:

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

答案 2 :(得分:0)

如果可能,我建议您将返回的JSON对象的结构更改为类似于下面的结构:

posts = [
    { 
    id : "post id",
    title: "Post title",
    content: "Post content",
    date : "post date",
    user : {
        id: "user id",
        name: "user name"
        }
    },
    ....
    ....
]

这应该有用。