AngularJS first removes the ref documents, then the parent

I have a delete function, but it is not well encoded. Sometimes it gives an error, because it gameis deleted before all stages. How can I call game.$remove()only after all stages have been successfully deleted? Thank you very much!

$scope.remove = function(game) {
    if(game) { 
        var milestonesToDelete = MilestonesService.query({ gameId: game._id }, function(milestonesToDelete) {
            if(milestonesToDelete) {
                for(var i = 0; i < milestonesToDelete.length; i++) {
                    milestonesToDelete[i].$remove();
                }
            }
        });

        game.$remove();

        for (var j in $scope.games) {
            if ($scope.games [j] === game) {
                $scope.games.splice(j, 1);
            }
        }
    } else {
        $scope.game.$remove(function() {
            $location.path('admin/games');
        });
    }
};
+4
source share
1 answer

It looks like you just need to remove the game after completing the milestone. So just paste this code inside the async callback:

$scope.remove = function(game) {
    if(game) { 
        var milestonesToDelete = MilestonesService.query({ gameId: game._id }, function(milestonesToDelete) {
            if(milestonesToDelete) {
                for(var i = 0; i < milestonesToDelete.length; i++) {
                    milestonesToDelete[i].$remove();
                }
            }
            game.$remove();

            for (var j in $scope.games) {
                if ($scope.games [j] === game) {
                    $scope.games.splice(j, 1);
                }
            }
        });

    } else {
        $scope.game.$remove(function() {
            $location.path('admin/games');
        });
    }
};
+3
source

All Articles