States. Angular and United
In this post I’ll talk a bit about managing state in AngularJS applications and post some photos I took on a trip to Atlanta + some other shots.
(Not a coder? Skip to the photos then)
Code Stuff
When working on projects where AngularJS is the primary framework in use, it’s very important to follow some good practices.
There are a lot of nice and resources online and I particularly like Todd Motto’s post on Rethinking AngularJS Controllers where he talks about abstracting the model from the controllers and passing more responsibility and state into services.
Trim the Controller and Work the Service
I totally agree with what’s stated on that post so I keep my controllers with minimum business logic, only acting as a ViewModel - glueing data to the template - and some event delegation.
I also try to follow the Separation of Concerns principle, so I keep the services small and self-contained. This way, it’s the controller’s responsibility to fetch the data from each service the controller depends.
Persisting
There are some projects - made with AngularJS or not - that we get to a point where we need to persist some state across utilizations so that the experience is easier / quicker, or simply because the requirements specify so, and in certain cases we make use of some storage solutions for that.
Be it session storage, local storage, cookies, etc, we end up saving and restoring states at different points of the application.
In this cases, if we’re following the strategy described above, we end up with a lot of Services accessing the storage. In some extent, this turns into a sloppy implementation as:
- a) those services access the same storage solution in different parts of the code (and in different times) of the application;
- b) as simple as the storage solution can be, there are always specificities that need to be dealt with (parsing/invalidating/namespacing/etc)
Angular States
For this reasons, at Mindera we started working with the angularStates service. It’s a service meant to be used as a top layer on the AngularJS app, for saving, restoring, invalidating services/factories states.
Note: Currently it’s only implemented on top of the localStorage.
It relies on 3 main methods:
register
your service/factory in the StatesService, passing a key (usually the service name) and the properties you want to keep track of. You’re able to specify default values (in case the value retrieved is invalid) and an expiration time for each value.saveState()
to save it to storage.recoverState()
to try to retrieve it from storage.
Please check the repo and try it if you find it useful! :)
Now, on to the photos!
Photo Stuff
See ya soon,
A. Capelo
Tweet