NoNameProvided NoNameProvided - 3 months ago 56
AngularJS Question

How destroy a controller with ui-router in ionic framework

I have an ionic angular app, and I use the ui-router. My problem is that the controllers doesn't get destroyed when I navigate from their state to a new one. So when a user log out and an another log in they can see the first user data because the controllers still contain the data for the first user. How can I destroy the controllers on state change?

Here is an example config:

$stateProvider.state('root.module.view', {
url: '/path',
views: {
'content@root': {
template: require('./template.jade'),
controller: 'MyController',
controllerAs: 'myCtrl'
}
}
});

Answer

Ok I have found the answer, the root of the problem is that Ionic cache the views for faster page changes, but by doing so it prevents the destroyation of the controllers on page leave.

There is more way to change this behaviour. Firstly you can set the cache attribute in the route config like this:

$stateProvider.state('root.module.view', {
  url: '/path',
  views: {
    'content@root': {
      cache: false,
      template: require('./template.jade'),
      controller: 'MyController',
      controllerAs: 'myCtrl'
    }
  }
});

Or you can entirely disabling it with the $ionicConfigProvider this way:

  $ionicConfigProvider.views.maxCache(0);

The third option is to use the attribute:

<ion-view cache-view="false" view-title="My Title!">
...
</ion-view>