Ionic View Lifecycle 101

Ionic is one of the premier open-source frameworks for developing cross platform mobile apps for Android and iOS. As you likely know it is based on the Cordova project, an open-source toolkit for developing apps using HTML, CSS, and Javascript. We've had great success developing a number of apps using the Ionic framework including our recently launched wrestling scorer and stat tracker Backpoints. Today, we're going to be taking a quick look at some of the events in the view lifecycle of an Ionic app.

Loaded: First things's first. The loaded event is called only when the view is first loaded and added onto the DOM:

$scope.$on('$ionicViewLoaded', function() {
    // dynamically load content or assets
})

Don't let the name 'ViewLoaded' fool you, this is probably not the one you want to use in most common cases.

Enter: This event is called each time you enter the view regardless of any caching. In many, cases were you are loading a small amount of data to fill in fields on your view:

$scope.$on('$ionicViewEnter', function() {
    // simple object setup
    $scope.data.myModel = dataSource.get(object);
})

The related events $ionicViewBeforeEnter' and $ionicViewAfterEnter work in much the same way but, as their names imply, are only called before and after the view is entered.

Leave: This is exactly what it sounds like. When the user navigates from the view the $ionicViewLeave event is called. The leave event is a great place to do cleanup including any memory management that your app may require or resolve any outstanding state issues / user changes that haven't yet been committed.

Unload: The view lifecycle begins with putting the view and its elements on the DOM. The $ionicViewUnloaded is where it ends and takes those elements off of the DOM. It's also important to note that when this event is called the view's controller is also destroyed. In most cases, theres's not much you are going to want to do on this event and if you find yourself with a lot of code in it, consider moving them to another event such as $ionicViewLeave or $ionicView.afterLeave.

That's it for our quick tour of the view lifecycle in Ionic. Let us know what you think on Twitter and if you'd like to get a hybrid mobile app developed, please fill out the contact on this page.