Menu

How to do loading spinners, the Angular way.

14 November 2014

Updated on 6/17/16

Pro tip: A lot of the code here are examples of how to do things that aren't actually in the final spinner package, such as building an HTML 5 animated spinner or going through code step by step with lots of comments for learning. If you skim the post and think "that's too much code" like several commenters seem so intent on saying then by all means do it however you think is best. Nobody is forcing you to do anything. Take it from me though, I've witnessed the twist my colleagues get themselves into when trying to toggle a simple spinner half way around their app, traversing scope trees and broadcasting events down the entire scope chain, injecting $rootScope everywhere, etc. Before this all I've seen are ugly hacks that require even more code.

Maybe there's an even more elegant way to bake spinners into any angular app with minimal effort but I've yet to see it. Feel free to enlighten me, but just telling me "that's a lot of code" helps nobody and is actually not even true. Either that or we have very different ideas about what "a lot of code" is. You can see the entirety of the the module here, which as you can see is nothing but a single service and a single directive, both of which are rather small in my opinion, but what do I know ¯\(ツ)/¯

One interesting problem I had to solve recently was how to elegantly deal with loading spinners on the page without violating separation of concerns. Many times, the spinner element is in an area of the DOM controlled by the relevant controller and you can simply toggle a variable in scope and it just works. For example:

This works great, but what if your spinner is in a DOM tree that isn't managed by the controller that needs to show it? What if you need to hide/show spinner(s) from within a service? You then need to start thinking through a somewhat more complex solution to get at that spinner without making the nasty call to angular.element('#mySpinner').show() (which is just a wrapper around JQuery or JQlite). If you stoop to that level then you're coupling the DOM with your controller logic and you make it extremely difficult to test in isolation.

Even if you manage to solve this scenario, how then do you solve situations where you need to show/hide multiple loading spinners? It's often smart to hide every loading spinner on the page in some sort of global error handler, ensuring that any uncaught exceptions don't end up leaving an endless spinner behind to frustrate the user. If we want to do this while playing nice with Angular and keeping our app testable, then we need to come up with a generic solution that can be implemented anywhere.

The directive:

Of course, we love directives and some kind of spinner directive seems to make immediate sense. My first instinct at this point was to create a directive that would register a few different event listeners on $rootScope. It could listen for events like show-spinner-my-spinner, hide-spinner-my-spinner, show-spinner-group-foo, hide-spinner-group-foo, show-all-spinners, and hide-all-spinners. That idea lasted all of ten seconds in my brain before I realized just how unwieldy that solution was going to be. An evented system sounds like the magic bullet we need, but what happens when in a large single page app, two people create spinners with the same name? Well, two event listeners for the same name are going to be registered. When logic triggers an event that is supposed to show a single spinner, it's going to show both spinners with duplicate names.

What we really need here is the ability to register spinners with a service and allow that service to keep track of them all in an intuitive way. Rather than subscribe to six different events in every instance of our spinner directive, each directive will simply register itself with a service. Here is an example of a directive I recently put together to do just that.

See how the directive calls spinnerService._register(api)? Our service's _register method accepts an API object for the spinner and files it away for later interaction. Each spinner that registers with the spinner service has a unique name, making it easy to keep track of all our spinners.

The directive would look something like this:

<spinner name="mySpinner"></spinner>

It can be shown by default like this:

<spinner name="mySpinner" show="true"></spinner>

The show option is a two-way bound variable. You can pass in a simple true/false, but it also allows you to pass a variable from the parent scope so that you can hide/show the spinner based on your application's state.

You can also stop the spinner from registering with the spinner service if you need to:

<spinner name="mySpinner" register="false"></spinner>

If you do stop the spinner directive from registering itself with the service then you'll need a manual way to interact with it. You can get ahold of the spinnerApi for that spinner by supplying an expression to the onLoaded option.

Your expressions also have access to spinnerService for convenience, but that can also be injected like any other Angular service.

Transclusion

I'm not done showing off our directive quite yet! Did you happen to notice this little tidbit in our directive template just beneath the image element?

<span ng-transclude></span>

Transclusion is Angular's fancy term for allowing you to nest markup within a directive tag and have that markup included somewhere inside the resulting directive template. The ngTransclude directive specifies where transcluded content should be placed. Through the use of transclusion it is possible to supply custom HTML to our spinner instead of or in addition to, our loading graphic. For example, we could make an HTML 5 animation and use it as our spinner instead of an animated gif:

Thanks to Tobias Ahlin for the fancy loading animation. With this we now have a loading spinner that is made entirely out of CSS and placed inside a directive that will manage it for us. Here is a working demo of the fancy spinner above. Supply a dummy email and password and click "Login" to see the spinner in action.

With the ability to include your own custom markup your spinners can now be almost anything you need them to be. One type of animation you may want to put in your spinner would be an HTML5 <canvas> animation. That's absolutely possible, but the unique thing about <canvas> is that you draw/animate on it via JavaScript. If you want to hide and show a canvas animation at will then you need to run the animation JavaScript logic whenever the spinner is shown. To that end our directive also provides onShow and onHide options. Both options accept an expression just like our onLoaded option does. The onShow expression will be evaluated whenever the spinner is shown, and obviously the onHide expression will run whenever the spinner is hidden.

The service:

Our service needs to store all of our spinner directive API objects and expose some kind of service API for interacting with them all. Our spinners have unique names so we need a way to show a spinner by its name. We also have the option to specify a group on each spinner so we'll need a way to show all spinners registered with a specific group. Lastly, it would be nice if there were a way to show/hide all spinners regardless of group.

Our spinnerService allows us to inject it anywhere we need it and invoke a single spinner, a group of spinners, or all spinners. You can see that the _register function takes in the spinner API and adds it to the spinners object. Once a spinner is registered, showing it is as easy as spinnerService.show('mySpinner'). Showing a group of spinners is simple as well, spinnerService.showGroup('foo'). If we really need to, we can even show every spinner registered with the service, spinnerService.showAll(). Though in reality only the hideAll method is really ever used, usually inside of a global error handler to ensure there are no left behind spinners after uncaught exceptions.

Now your spinner(s) can exist anywhere in the DOM and you don't have to implement complicated scope hierarchy traversal logic or emit a bunch of arbitrary events on $rootScope. Every spinner will automatically register itself with the service, then you need only inject that same service anywhere you need it.

I took the liberty of turning this solution into a Bower package. You can find it here if you'd like to use it. Here is a working demonstration as well: