vincentf vincentf - 2 months ago 15
AngularJS Question

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);
})

Nix Nix
Answer

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);
});