Omar
Omar

Reputation: 3060

AngularFire (AngularJS) voting app cant iterate over firebase data

I am using ng-repeat to print array data from Firebase. As seen below; foreeach quote I want to count all the votes assosiated with it but any attempt to iterate results in undefined

my Markup

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

my controller

    app.controller('account', function ($scope, $timeout, $rootScope, $location, $firebaseObject, $firebaseArray) {

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

         //======== item totals ========//
        $scope.total_votes = function(itm) {

            // attempt ONE
            var itm_votes = $scope.quotes_obj[itm.$id].votes;
            console.log(itm_votes); // returns "{-KzFkQYHWKwbAPjIekWz: "sad", -KzLT76T14doKgYbjRc1: "wow"}"
            console.log(itm_votes.length); // returns "undefined"


            // attempt TWO
            console.log(itm.votes) // returns "{-KzFkQYHWKwbAPjIekWz: "sad", -KzLT76T14doKgYbjRc1: "wow"}"
            console.log(itm.votes[0]) // returns "undefined"
            console.log(itm.votes.length) // returns "undefined"

            // count votes
            var counts = {};
            for (var i = 0; i < itm_votes.length; i++) {
                counts[itm_votes[i]] = 1 + (counts[itm_votes[i]] || 0);
                if(i == itm_votes.length){
                    console.log('done');
                }
            }

            return counts;
        };


    });

Here is a picture of a single quote on my firebase database enter image description here

Does anyone know why the index is undefined for the data? I am open to new ways to count all the like votes if you see something wrong with this approach

anything helps. Thanks!

Upvotes: 1

Views: 73

Answers (1)

Omar
Omar

Reputation: 3060

I had to $.map to convert the obj to array.

$scope.total_votes = function(itm) {
    var itm_votes = $.map($scope.quotes_obj[itm.$id].votes, function(value, index) {
        return [value];
    });
    console.log(itm_votes.length);
    var counts = {};
    for (var i = 0; i < itm_votes.length; i++) {
        counts[itm_votes[i]] = 1 + (counts[itm_votes[i]] || 0);
        if(i == itm_votes.length-1){
            console.log('done');
            console.log(counts);
        }
    }
    return counts;
};

Upvotes: 1

Related Questions