我使用以下代码在我的firebase中展平了数据。但是当我想要显示最喜欢的用户帖子列表和ng-repeat时,模板会重复第二次并且完全空白。我怎么能纠正这个?
"Post": {
"xKkdfjjfld856i": {
"name": "My first post",
"author": "Miguel"
},
"xKkdfjj556FGHh": { ... },
"xK499DF6FlHjih": { ... }
},
"users": {
"John": {
favorited_posts {
"xKkdfjjfld856i": true,
"xKkdfjj556FGHh": true
}
},
"Mia": { ... },
"Patrick": { ... }
},
HTML:
<div ng-repeat="post in favoritedPosts track by $index">
<div class="card post-card">
<h1>{{post.name}}</h1>
<p>{{post.author}}</p>
</div>
</div>
控制器:
var userRef = new Firebase("https://myApp.firebaseio.com/users")
var userFavoriteRef = userRef.child($scope.user_id).child("favorited_posts")
var favoritedPosts = $firebaseArray(userFavoriteRef)
userFavoriteRef.once("value", function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key();
var postRef = new Firebase("https://myApp.firebaseio.com/Posts")
postRef.child(childSnapshot.ref().key()).once('value', function(postSnapshot) {
console.log("Look",postSnapshot.val());
$scope.favoritedPosts = postSnapshot.val();
});
});
});
答案 0 :(得分:3)
尝试使用$firebaseArray
和$getRecord
(documentation)根据对象键获取对象值。然后,您将获得所需的一切,而无需循环使用同步调用。
var userRef = new Firebase("https://myApp.firebaseio.com/users")
var userFavoriteRef = userRef.child($scope.user_id).child("favorited_posts")
$scope.favoritedPosts = $firebaseArray(userFavoriteRef)
var postRef = new Firebase("https://myApp.firebaseio.com/Posts")
$scope.posts = $firebaseArray(postRef)
<div ng-repeat="post in favoritedPosts">
<div class="card post-card">
<h1>{{posts.$getRecord(post.$id).name}}</h1>
<p>{{posts.$getRecord(post.$id).author}}</p>
</div>
</div>