Friday, May 23, 2014

A visual representation of seeding before manually bootstrapping AngularJS

If you're just here for the demo, here you go:

The Problem

As a developer using AngularJS, sometimes you'll want to seed data into some data source (local storage), or make some async calls to a server before your AngularJS application actually loads.  There are good reasons to avoid this at all costs, except when you're trying to replicate an existing user experience.

Take the case of local storage. Sometimes when you deploy a new version of your AngularJS application, you want to see how it works with existing user data. That is, you don't want to assume your user has no data. Ideally you're writing perfect code and you're handling all the null cases correctly, but we don't want to assume that with production data, right?

This process is critical because you don't want your application to incorrectly handle, corrupt, or delete any user data stored in these source, but how do we test this experience without writing hard coded config structures (which are actually data) directly into our Angular application. We want to separate these concerns and bring seeding outside of the Angular application so that we can accurately replicate the user experience when we actually bootstrap the application.

The Solution

To accomplish this, we're going to remove the ng-app attribute from our index.html. By doing so, we ensure that the application is not bootstrapped until we actually want it to be.

Since this is a complex topic, I've created a visualization that I think shows the AngularJS manual initialization process pretty well. Keep in mind I've added in UI-Router and several wait functions so that your eyes have a chance to see each step in action. As a visual learner, this helped me to understand the process from start to finish.

You can see the example Plnkr here:

PS. This all came about while diagnosing an issue for the ng-inspector extension/plugin. Check that excellent project our here:

Happy seeding and bootstrapping!