On Ionic view caching and its effect

For a multiple view Ionic app, the controller for the state is attached to <ion-content> directive or tag. A few lines below are usually included in individual template (html) – note you don’t need to add ng-controller attribute.

<ion-view view-title="Home">
    <ion-content ng-controller="HomeCtrl">
       <!-- The content of the page -->
    </ion-content>
</ion-view>
 

Caching

By default, views are cached to improve performance. When a view is navigated away from, its element is left in the DOM, and its scope is disconnected from the $watch cycle. When navigating to a view that is already cached, its scope is then reconnected, and the existing element that was left in the DOM becomes the active view. This also allows for the scroll position of previous views to be maintained.

Caching can be disabled and enabled in multiple ways. By default, Ionic will cache a maximum of 10 views, and not only can this be configured, but apps can also explicitly state which views should and should not be cached.

Note that because we are caching these views, we aren’t destroying scopes. Instead, scopes are being disconnected from the watch cycle. Because scopes are not being destroyed and recreated, controllers are not loading again on a subsequent viewing. If the app/controller needs to know when a view has entered or has left, then view events emitted from the ionView scope, such as $ionicView.enter, may be useful.

Personal note: you include $scope.$on(‘$ionicView.enter’, function() { });  in the controller js file to catch the event and then execute the code inside function().

By default, when navigating back in the history, the “forward” views are removed from the cache. If you navigate forward to the same view again, it’ll create a new DOM element and controller instance. Basically, any forward views are reset each time. This can be configured using the $ionicConfigProvider:

$ionicConfigProvider.views.forwardCache(true);

Disable cache globally

The $ionicConfigProvider can be used to set the maximum allowable views which can be cached, but this can also be use to disable all caching by setting it to 0.

$ionicConfigProvider.views.maxCache(0);

Disable cache within state provider

$stateProvider.state('myState', {
   cache: false,
   url : '/myUrl',
   templateUrl : 'my-template.html'
})

Disable cache with an attribute

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