sickk
sickk

Reputation: 55

AngularJS: Change route before a redirect countdown runs out but the redirect starts

I have got a problem with a simple login/logout page. When a user logs in/out, a success message with a countdown is shown. When the timout expires, the route changes.

However, the user can navigate before the countdown ends (using the menu or a button). The problem is that even when using the menu, the login/-out timeout still fires.

Here the code of the counter:

$scope.onTimeout = function(){
        $scope.counter--;
        $scope.timeoutCountdown = $timeout($scope.onTimeout,1000);
        if($scope.counter === -1){
            $scope.safeApply(function() { $location.path("/home"); }); //if the user isn't logged...redirect to main
        }
};

And this is the code that change the location when press the button:

$scope.redirectToHome = function() {
        $scope.safeApply(function() { $location.path("/portale"); });

};

Does anybody know why the timeout fires after changing the controller?

Thanks in advance

Upvotes: 2

Views: 776

Answers (1)

thomaux
thomaux

Reputation: 19738

The issue you're having is due to the fact the timeout is not cleared when the $scope is destroyed.

You need to manually clear the timeout by listening to the $destroy event. This event originates from Angular and is thrown whenever a $scope is destroyed. Try adding the following to your controller (I did not test this, so consider this pseudo code)

$scope.$watch('$destroy', function(){
    $timeout.cancel($scope.timeoutCountdown);
});

Edit:

You could also do this right before changing the route:

$scope.redirectToHome = function() {
    $timeout.cancel($scope.timeoutCountdown);
    $scope.safeApply(function() { $location.path("/portale"); });
};

Just keep in mind that if you have other redirect possibilities (i.e. other buttons the user could use to navigate from the login/-out page), you'd need to do this for each of those (or preferably wrap it in a method).

Upvotes: 2

Related Questions