Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In angular, how to use cancel an $interval on user events, like page change?

Tags:

angularjs

Angular documentation about $interval is saying :

Note: Intervals created by this service must be explicitly destroyed when you are finished with them.

but it's not explaining how to destroy the $interval.

If for example I have a directive containing this code :

$interval(function() {     for (var i in myArray) {         // do domething     } }, 5000); 

How can i destroy it when the user changes the page for example?

like image 960
François Romain Avatar asked Jan 26 '14 14:01

François Romain


People also ask

What is$ scope in angular?

$rootScope is a parent object of all “$scope” angular objects created in a webpage. $scope is a child object that is used to bind the HTML(view) & Javascript(Controller) in a webpage. It is created with the ng-app directive. It is created with the ng-controller directive.

How many child scopes can an AngularJS application have?

Scope Hierarchies Every angularJS application can have only one root scope as it is the parent scope. But it can have more than one child scope. New scopes can be created by directives which are added to parent scope as child scope.


1 Answers

Whenever the user changes the page, the scope associated with the controller of the route (/page1 in the example below) will be sent a $destroy event. You can cancel that $interval in a listener to that event:

app.config(function ($routeProvider) {      $routeProvider.when('/page1', {           template: '<div>Page Content</div>',           controller: PageController       });      // ... });  function PageController($scope, $interval) {     var intervalPromise = $interval(function () { /* ... */ }, 5000);           $scope.$on('$destroy', function () { $interval.cancel(intervalPromise); }); } 
like image 101
musically_ut Avatar answered Oct 12 '22 22:10

musically_ut