Domanda

I have an issue with a recursive function call in one of the view of my app:

The structure is the following:
ng-view -> Home
ng-view -> TrackPosition (using phoneGap)

on my TrackPosition view I have this function :

$scope.printDistance =function printDistance()
{
     if (isPositionAvailable($scope.gps_position.Latitude))
        {
            //Print Distance between 2 points
        }
        else
        {
            console.log("### No position to calculate Distance...")
            setTimeout(function(){$scope.printDistance();},1000);
        }

}

If there is no GPS position available (from the phone) I call with timeout the function recursively. so each seconds it will check if GPS position is available to calculate distance from you to another point.

All is working fine on the view. However, if I left the TrackPosition view (before getting GPS coordinates) to go on the HomePage, I noticed that the function is still calling itself recursively (thanks to the console.log).

The question: Is there anyway to flush the scope?
I noticed as well memory leaks between ng-view (but it's apparently a known issue)




Note:
I am already doing:

myApp.run(['$rootScope', '$templateCache', '$location',
    function($rootScope, $templateCache, $location) {
        $rootScope.$on('$viewContentLoaded', function() {
            $templateCache.removeAll();

        });
    }
]);

In order to try to avoid too much memory leak.

È stato utile?

Soluzione

Try this piece of code (untested):

var timeoutPromise = null;

$scope.printDistance = function printDistance() {
    if (isPositionAvailable($scope.gps_position.Latitude)) {
        //Print Distance between 2 points

        timeoutPromise = null;
    } else {
        console.log("### No position to calculate Distance...")
        timeoutPromise = $timeout(function() {
            $scope.printDistance();
        }, 1000);
    }
}

$scope.$on('$destroy', function() {
    if (timeoutPromise) {
        $timeout.cancel(timeoutPromise);
    }
});

First of all, prefer using $timeout instead of setTimeout. $timeout also calls $apply() (digest and re-render). setTimeout does not so you have to call it yourself (you don't seem to call it, though).

The actual solution is to listen to the $destroy even which is fired when you navigate back to Home. At that point you stop the async task.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top