0

I am using AngularFire in my AngularJS project. In the following HTML you can see I am passing the quote item in to the total_votes function in my controller.

    <div ng-repeat="quote in quotes" ng-init="total_votes(quote)">
        {{quote.name}}
    </div>

This is where quotes came from

    // get quotes
    var ref = firebase.database().ref().child('quotes');
    $scope.quotes_obj = $firebaseObject(ref);
    $rootScope.quotes = $firebaseArray(ref);

this is what the function looks like

    $scope.total_votes = function(itm) {
        console.log(itm.votes)
        console.log(itm.votes)
        console.log(itm.votes[0])
        console.log(itm.votes.length)
    };

This is what is printed

console.log(itm.votes)

    {
      "quote": "untitled",
      "recorded_by": "-KzFkQYHWKwbAPjIekWz",
      "votes": {
        "-KzFkQYHWKwbAPjIekWz": "sad",
        "-KzLT76T14doKgYbjRc1": "wow"
      },
      "who": "null",
      "$id": "-KzKz7EyCSPkPl0YDvfa",
      "$priority": null,
      "$$hashKey": "object:15"
    }

console.log(itm.votes) {"-KzFkQYHWKwbAPjIekWz":"sad","-KzLT76T14doKgYbjRc1":"wow"}

console.log(itm.votes[0]) undefined

console.log(itm.votes.length) undefined

How do I iterate over the votes from quotes? Why is Length Undefined? how come I cant reach the individual items via index like itm.votes[0]?

1 Answer 1

1

Keep in mind that $firebaseObject() and $firebaseArray() are asynchronous. You have to wait for the data to download over the network. While this usually doesn't take long it still means it won't be available immediately.

You see the data appear in your view because of AngularJS's dirty checking system. When the data is available Angular automatically populates the view since it knows about the values on $scope.

I've written about this in a blog post and done a screencast covering it as well.

You can iterate the data in your view with ng-repeat.

<div ng-repeat="item in items">
  {{ item }}
</div>

This way you can rely on the view to always keep your data updated.

In your case this will be tricky because your "votes" are nested in your "quotes". I highly recommend breaking out the "votes" to their own top level data structure. To keep the relationship you can share the key between them.

{
  "quotes": {
     "a": {
        "name": "A"
     }
  },
  "votes": {
     "a": {
        "count:" 11
     }
  }
} 

Alternatively you can use a router resolve to resolve the data using the $loaded promises. Which the blog post covers.

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

1 Comment

wow that is a different way to look at it... Iterating in the view and un-nest votes is what I will do.

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.