0

Below is the code i use to query my firebase in search of players whose ids match the numbers in an array:

.controller('mySquadCtrl', ['$scope','$location','$firebaseArray','$firebaseAuth','CommonProp', 'DatabaseService',
 function($scope,$location,$firebaseArray,$firebaseAuth,CommonProp, databaseService){


 var uid = CommonProp.userUid();
 $scope.uid = uid;
 $scope.username = CommonProp.getUser();  

 if(!$scope.username){
$location.path('/welcome');
 }

databaseService.users.child(uid).once('value', function(usersSnapshot){
var users = usersSnapshot.val();
var total = users.total;
var team = users.teamname;

$scope.pick = total; 

var orderedPlayers = databaseService.players.orderByChild("id");
$firebaseArray(orderedPlayers)
        .$loaded(function(loadedPlayers) {
        var normalizedPlayers = loadedPlayers.reduce(function(acc, next) { acc[next.id] = next; return acc; }, {});
        var selectedPlayers = $scope.pick.map(function(num){
            return normalizedPlayers[num];
        });
        $scope.players = selectedPlayers;
                    $scope.sum = function(items, prop){
                    return items.reduce( function(a, b){
                    return a + b[prop];
                    }, 0);
                    };
        $scope.totalPoints = $scope.sum($scope.players, 'goals');    
        $scope.teamname = team;

}, function(err) {
    console.log(err);
    $scope.players = [];
});

 });


 $scope.logout = function(){
 CommonProp.logoutUser();  
}; 

}]);

If the user is not logged in, the page redirects them to the 'home page'.

My issue is that the $scope.totalPoints result does not update in realtime even though the $scope.players "goal" value does when i change it in the database directly.

IS there a way to make the $scope.totalPoints update in realtime as I change the values to the $scope.players values in the database?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Deji James
  • 367
  • 6
  • 20

1 Answers1

0

The $loaded promise is only called once: when the initial data has been loaded from the database. It is not called on updates.

To have an auto-updating sum, you'll instead want to extend $firebaseArray. See the AngularFire documentation for an example of extending an array to include a total. For another good example, see the answer to this question.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • I dont quite understand how $extend works. All the examples use it within a factory. As I do not have a factory in my code does that mean that I have to create a factory before the $scope.totalPoints function will update ? – Deji James Sep 21 '17 at 15:29
  • Yes. That is indeed what the example does. – Frank van Puffelen Sep 21 '17 at 19:01