In AngularJS, how to detect when user leaves template/page?

Curt picture Curt · Dec 14, 2012 · Viewed 69.5k times · Source

I am using the Javascript command: setInterval. I like to stop it when the user leaves the page.

This code seems to work well: http://jsfiddle.net/PQz5k/

It detects when a user leaves a page. It executes Javascript code when a user clicks on a link to go to a different HTML page or URL, or if user reloads page.

However, it does not work when I go from one AngularJS template to another. As an example, if I am at template1.html, I want the Javascript code to do something in Controller1.js when the user leaves template1.html to go to template2.html. What is the equivalent of this code below in AngularJS?:

$(window).on('beforeunload', function() {
    return 'Your own message goes here...';
});​

Answer

Mathew Berg picture Mathew Berg · Dec 17, 2012

I think you have two controllers, one for each template like this:

function Controller_1($scope...){
    ...
}
function Controller_2($scope...){
    ...
}

Well, when you switch from one template to another there's an event that's fired called $destroy, you can read up on it here http://docs.angularjs.org/api/ng.$rootScope.Scope#$destroy

Let's say I'm switching from the template with Controller_1 to the template with Controller_2. Controller_1 has an interval I'd like to stop. You can accomplish this with:

function Controller_1($scope, $interval...){
    var myInterval = $interval(...);
    $scope.$on("$destroy", function(){
        $interval.cancel(myInterval);
    });
}

This will mean that when the $scope for Controller_1 is destroyed, the event will be called and the interval will be cleared.