我是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对象中?
答案 0 :(得分:1)
ngRepeat为每个条目创建一个新范围。该范围将包含$index
,用于数组中的当前偏移量。由于它是一个新的范围,变量posts
现在位于$parent
范围内。
假设posts
和users
包含并行数据并且是数组。您可以使用users
在$index
中查找数据。
<h1>{{$parent.posts.users[$index].username}}</h1>`
答案 1 :(得分:0)
如果没有看到posts
和users
对象的结构,很难准确说出,但一般的想法是使用带有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"
}
},
....
....
]
这应该有用。