1

What I am trying to do:

I want to output all of the books in the book node on my home page. What I need is an array of objects that contain all of the books in the book node so that I can loop through them using the ng-repeat directive in AngularJs. In the code below, when I console log the data, I get an object of objects, which cannot be used with ng-repeat. Another issue that I am having is when I try to output the $scope.allBooks variable on to the page, nothing appears. Can anyone help me with this?

Using Javascript SDK not Angularfire https://firebase.google.com/docs/

// Main Controller
firebase.database().ref('books').on('value', function(snapshot) {
    var data = snapshot.val();

    $scope.allBooks = data;
    console.log(data);
});


// Book Node in Firebase
books : {
    id : {
        title: 'The Hunger Games',
        author: 'Suzanne'
    },
    id : {
        title: 'Harry Potter and the Order of the Phoenix',
        author: 'J.K.'
    }
}

2 Answers 2

5

If you don't want to use angularfire you'll need to let angular know to run an update.

// Main Controller
firebase.database().ref('books').on('value', function(snapshot) {
    var data = snapshot.val();

    $scope.allBooks = data;
    console.log(data);
    $scope.$apply();
});

Just add in the $scope.$apply() to let angular know to update.

Sign up to request clarification or add additional context in comments.

Comments

0

You can most certainly use objects with ng-repeat on objects with the proper syntax. This is explained on the ng-repeat documentation page.

For example:

<div ng-repeat="(key, value) in myObj"> ... </div>

But this will break the order of items, so it's definitely not a recommended approach. Instead, you should use the forEach method to iterate children in the proper order, and build the array yourself.


If you use the Firebase JS SDK directly, Angular will not be notified of the changes to your data. You must trigger a digest cycle manually, so the scopes can be re-evaluated.

One of the ways to do it is by using $timeout to wrap scope manipulations. This was named a best practice in the old Firebase documentation.

   // Main Controller
   firebase.database().ref('books').on('value', function(snapshot) {
       var data = snapshot.val();
       console.log(data);
       $timeout(function() {
           $scope.allBooks = data;
       });
   });

1 Comment

Thanks a lot! @vzsg

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.