Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detect when angularjs route controller goes out of scope?

I have a controller that is attached to a route. The controller constantly polls the server using $timeout. When the route changes, I need to stop polling, and start it again when the route changes back.

Please help.

Here is my code:

(angular
 .module('app.controllers', ['ng', 'ngResource'])
 .controller('myContr', [
     /******/ '$scope', '$resource', '$timeout',
     function ($scope,   $resource,   $timeout) {
         function update() {
             $resource('my-service').get({}, function (d) {
                 // ...use data...
                 $timeout(update, UPDATE_INTERVAL);
             });
         };
         update();
     }
 ])
);
like image 418
akonsu Avatar asked Oct 21 '22 05:10

akonsu


1 Answers

  • Save the return value (a promise) from $timeout (to a $scope property).
  • Register a $destroy event handler on your scope.
  • Call cancel() on that $timeout promise when the event handler triggers.

When the route changes back, the controller will get recreated, so your existing code should start up the polling again.

like image 81
Mark Rajcok Avatar answered Oct 24 '22 05:10

Mark Rajcok