YngDev31 YngDev31 - 5 months ago 37
AngularJS Question

Firebase & Angular - Retrieve and display flattening data

I have flattening data in my firebase with the following code. But when I want display favorite user posts list with ng-repeat, the template gets repeated a second time and comes out totally blank. How can I correct this?

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


Controller :

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

});
});

Answer

Try working with the $firebaseArray and $getRecord (documentation) to get the object value based on the object key. Then you will have everything you need without looping over assync calls.

Controller

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)

HTML

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