0

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

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

});
Community
  • 1
  • 1
Sam Palmer
  • 1,675
  • 1
  • 25
  • 45
  • 1
    suggest looking into using `angularFire`. All events using firebase directly require telling angular to run a digest since the data is being retrieved outside angular context. `angularfire` makes 3 way binding very simple – charlietfl Sep 14 '16 at 18:30
  • Thanks I'll look into that! – Sam Palmer Sep 14 '16 at 19:19

1 Answers1

1

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

KpTheConstructor
  • 3,153
  • 1
  • 14
  • 22