detect when angularjs route controller goes out of scope?
angularjs, javascript
Solution
- 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.
Problem
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(); } ]) ); ```