AngularJs and SpinJs (in Coffeescript)

SpinJs is a nice Javascript based way to creating a busy/loading spinner on your webpage. I'm going to quickly go through how you might integrated SpinJs with an AngularJs app so that the spinner appears when an Ajax request is sent, and disappears when the Ajax response is received.

First we will create and add interceptors. AngularJs makes this task incredibly easy and elegant. We will add the interceptors at configuration time to the httpProvider.

As you can see in the above we have only put annoying alerts whenever http requests are send or received. Users would not appreciate if we stopped here! Next we will define the logic to display and hide the spinner from SpinJs. We will define it as a Provider so that it will be available to us at Configuration time.

All Providers are required to expose a $get() function, but as we don't need to create multiple instances, we return null. Other than that, the above should be pretty straight forward. We store a reference to the spinner, and attach it to a DOM element so that we can retrieve it later to stop and delete it.

All that is left to do now is connect the above two pieces of code, and we do that by adding the Spinner function to the interceptor via Angular's powerful injection mechanism.

And that is it. Now you only need to add the interceptor to your root module and you are done! So elegant! So beautiful! That's Angular!

Credits

http://jsfiddle.net/dBR2r/8/

Comments

  1. any chance to see the javascript code instead of coffeescript ?

    ReplyDelete
  2. This is what the coffeescript.org compiler gives. Hope that helps!

    https://gist.github.com/halfbaked/5900137#file-spinangular-js

    ReplyDelete

  3. Cool article, thank you for sharing a beautiful and intuitive graphic example of the script! I was impressed
    Richard Brown due diligence data room

    ReplyDelete

Post a Comment

Popular posts from this blog

AngularJs: User friendly date display with AngularJs and MomentJs

Nerd Tree: A File Explorer with Mac Vim

Getting started with Grails functional tests using Geb + Spock