简体   繁体   中英

Watching for changes in $scope

Below is the code I use to bring the selected players from my firebase databse to my scope:

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


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

The problem is that when I change the number of goals from the firebase database, there is no real time change of the total nuber of points. ie $scope.players = selectedPlayers; updates in real time but $scope.totalPoints only updates after refreshing the page.

Is it possible to have the latter update in real time as well?

why to not just set it in the call back directly to be

$scope.players  = $scope.pick.map(function(num){ ...

rather than

var selectedPlayers = $scope.pick.map(function(num){

this will bind the results directly into the scope variable

Assuming

  • Angular 1.xx
  • $scope.totalPoints is a number (primitive)

It could be that $scope.totalPoints is being used by a child scope (maybe a nested directive or controller) and that is why the change did not get propagated to them. Try wrapping totalPoints inside and object.

$scope.state = {
  totalPoints: 0
};

Make the required changes in the template and firebase callback.

If that doesn't work try manually requesting a digest cycle using

$scope.$apply(function () {
  $scope.totalPoints = $scope.sum($scope.players, 'goals'); 
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM