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); }); } }); } })(); }); 
2
  • 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 Commented Sep 14, 2016 at 18:30
  • Thanks I'll look into that! Commented Sep 14, 2016 at 19:19

1 Answer 1

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

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

2 Comments

there is no $scope in a service
Can I do it using $rootscope though?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.