Run Function On Navigate Back

Hi everyone! Just wanted to share a solution I came across that might help someone else!

So I have an init function that I wanted to run every time a user spun up a particular controller. However, I can’t just put this code within the controller b/c ionic stores $scopes in history and does not recall the $controller when a user navigates back.

In other words, if you put alert('hello world'); in your controller, it will be called when the user goes to the page for the first time. But if they navigate to another page and come back… No hello world.

Solution:

$scope.$on('$stateChangeSuccess', function(e, toState) {
   if(toState.name === 'tab.profile') {
      // ...
   }
});

Just replace tab.profile with the name of your $state and the above snippet will not be called when the controller is initialized, but will on navigate back!

For anyone who is interested my use case for this is I have an $interval that I needs to be runing while the state is active. My snag was the controller initializes, the $interval on initial page load and everything is great. However, when the user navigates away the $interval is destroyed. So when we come back no more $interval. So this code allows me to spin that $interval back up when they come back!

Cheers!

1 Like