4

I've setup a controller to tick every few seconds, which in turn makes a restful call to a backend api. Everything is working as expected, except when I navigate to another section (handled by a separate controller), the tick continues to fire.

Is it possible to remove the controller from scope entirely?

Here's a paste of my current controller:

myApp.controller('SupervisorController', function($scope, supervisord, $timeout) {

    $scope.supervisord = supervisord;

    (function tick() {
        $scope.supervisord.fetch();
        $timeout(tick, 2500);
    })();
});
1
  • I'd be interested to know as well how you implemented tick with $watch. Would it be possible to add it to your question? Thanks in advance. Commented Jul 15, 2013 at 9:40

2 Answers 2

4

On http://docs.angularjs.org/api/ng.$rootScope.Scope it mentions that

Just before a scope is destroyed a $destroy event is broadcasted on this scope. Application code can register a $destroy event handler that will give it chance to perform any necessary cleanup.

This seems like exactly what you want.

Sign up to request clarification or add additional context in comments.

2 Comments

You were right, this is exactly what I was looking for. I ended up moving my tick into a $watch, and added a $destroy event which just deletes my service. Works perfectly, thanks!
@Mark Pitman: I have an issue similar to yours (i.e. polling a REST API). You wrote I ended up moving my tick into a $watch. Do you have some code sample somewhere that explains you solution ?
1

A workaround would be to use var myInterval = setInterval(tick, 2500); to get it going and later clearInterval(myInterval); to stop it again (or the analogous $timeout.cancel(myInterval)). For that you need access to myInterval in both controllers, so you might consider wrapping it in a Angular service.

3 Comments

I could do the same with the current approach, but that's going to require me to clear that interval in a separate controller right?
I'm curious to know if there's a way that I could 'watch' the controller, and if the user navigates to a different section of the UI, then unload/remove/destroy the controller completely?
If you're using routes, you probably could clear the timer in the $routeChangeSuccess callback.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.