Sam Palmer
Sam Palmer

Reputation: 1725

AngluarJS and Firebase, Updating table using services

I have a table I want to update with data I get from my firebase database. I know the firebase calls return a promise and the database call in then ran async, but even in the .then methods I can't seem to extract the async data into my table view.

To overcome the async part I have tried to used services (based on this answer Update scope value when service data is changed). I used the test callback method addValue()to test adding data. But when I use this callback inside the .then() of the firebase queries the data of the service is updated but it is not updated in the view.

routerApp.controller('leaderboardCtrl', function($scope, service) {

            $scope.data = service.data;

            service.getLeaderboard('Test1', 'TestGroup', 10);
            //service.getValues();


}).factory("service", function($rootScope, $q)
{
  return new (function AsyncTest(){
    this.data=[
        {name : "Sam" , score : 190}
    ]
    this.getValues=function()
    {
      var self=this;
        //self.data.push({name : "Sam" , score : 180});
        self.addValue();
        self.count++
    },
    this.count=0,

    this.addValue  =function(){
        var self=this;
        self.data.push({name : "Sam" , score : 180});
    }

    this.getLeaderboard = function(test, groupName, limit){
        var self=this;
        var uid = currentUser.uid;



     firebase.database().ref('/groupMembers/' + groupName).once('value').then(function(snapshot) {
        for(var user in snapshot.val()){
            firebase.database().ref('/tests/' +test + '/users/' + user).orderByChild("score").limitToLast(limit).once('value').then(function (snapshot) {
                       console.log('----LEADERBOARD----');
                       console.log(snapshot.val());
                       self.addValue();
                       console.log(self.data);

             });
            }
        });
    }
  })();

});

Upvotes: 0

Views: 44

Answers (1)

KpTheConstructor
KpTheConstructor

Reputation: 3291

This occurs often in Angular when using firebase. In your addValue() method try adding $scope.apply() after your push logic .

Example:

this.addValue=function(){
    var self=this;
    self.data.push({name : "Sam" , score : 180});
    $scope.apply();
}

$scope.apply() is used to update the view to reflect whats been done in your controller .

Hope this helps

Upvotes: 1

Related Questions