vincentf
vincentf

Reputation: 1499

Angular - How can I cancel $interval when state changes?

I'm using ngRoute. There is an $interval on dashboardController, How can I cancel it after leaving dashboard page? I tried to listen to $destroy. But it seems this event fires when I enter dashboard page. $routeChangeSuccess also doesn't work.

route:

    .when('/dashboard', {
        templateUrl: 'dashboard.html',
        controller: 'dashboardController',
    })
    .when('/applications', {
        templateUrl: 'applications.html',
        controller: 'appController',
    })

dashboardController:

var update = $interval(function() {
  //.....
},1000)

$scope.$watch('$destroy', function(e) {
  $interval.cancel(update);
})

Upvotes: 0

Views: 429

Answers (1)

Nix
Nix

Reputation: 58562

Ah I missed it the first time! You have $scope.$watch but it should be $on

The following code will cancel your interval on $destroy, which gets called when your route changes.

$scope.$on('$destroy', function(e) {
  $interval.cancel(update);
});

Upvotes: 2

Related Questions