Loading data at startup in a Ionic app

I’m working on a Ionic app that loads data at startup and also checks to see if this data is available everytime a view loads.

So to do this I’ve created a Service that loads the data, this I can call within the run function in the main JavaScript file, where I set up the routes using ui-router.

These run functions, and there can be more than one, are called when the application first runs.

.run(function(StartupService){
    StartupService.loadData();
})

In the above example I can call a function from my StartupService. The loadData() function then can load the data into localStorage so it is accessible when offline.

This was all fine, but I also wanted to check when a view loads to see if the data is accessible from local storage. Looking through the great documentation on the Ionic website there are a set of events that the ion-view has including:

  • $ionicView.loaded
  • $ionicView.enter
  • $ionicView.leave
  • $ionicView.beforeEnter
  • $ionicView.beforeLeave
  • $ionicView.afterEnter
  • $ionicView.afterLeave
  • $ionicView.unloaded

All these lifecycle events can be listened for, using the $scope.$on event handler.

So I used the $ionicView.enter event to make a call to see if the data was available in local storage.

This may not be the ideal approach, but it does work. The one thing I did get from this was the use of the event lifecycle for views and how it can help to tie into them.

A great article on these views and the lifecycle events is Navigating the Changes from the Ionic blog.