更新函数实时结果

时间:2017-09-19 20:55:27

标签: javascript angularjs firebase firebase-realtime-database angularfire

下面是我用来查询我的firebase以搜索其id与数组中的数字匹配的玩家的代码:

.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();  
}; 

}]);

如果用户未登录,页面会将其重定向到“主页”。

我的问题是,即使$scope.totalPoints“目标”值在我直接在数据库中更改时,$scope.players结果也不会实时更新。

有没有办法实时更新$scope.totalPoints,因为我将值更改为数据库中的$scope.players值?

1 个答案:

答案 0 :(得分:0)

$loaded承诺仅被调用一次:从数据库加载初始数据时。它不会在更新时调用。

要获得自动更新金额,您需要扩展$firebaseArray。请参阅AngularFire documentation for an example of extending an array to include a total。有关另一个好例子,请参阅the answer to this question