Creating a Simple Loading Angular Directive

I am working on an Angular Project that will call an API server.  It would be nice if adding a animation that indicating the page is waiting for server’s response.  There are many ways to do it such as using ng-show and ng-hide to show and hide the loading page.

Also, I found creating CSS loading is pretty simple, so I would like to use it on my page.  Loading page from looks very nice, you may generate the style you like.  Only problem is CSS animation including a long line of HTML code like this:

and also it’s style file loading.css.

If I include every page for API request that it does not look that good.  Therefore, I created a Angular Directive for this.

Instead adding that long line of code on every page, now I only need to include something like this:

The Directive:

and the template file for the directive:

To use this, you will create a boolean variable “loaded” to the $scope. Your controller will be look like this GIST.  I am using ng-hide and ng-show to hide and show the loading page and the content.

If everything works, the tag spin-loading should be replaced by the template file (directives/spinLoader/spinLoader.html) and <div>{{ loadContented }} </div> should be included inside <div ng-show=”loaded” ng-transclude></div>.

This is GIST that I created for example.  (If there is any mistake, please correct me because I just did a quick clone from my code and modify for sample)

Loading Spinners With AngularJS and Spin.js by Ankur Sethi’s Blog

I created a sample in JSFiddle note: There are small different in my code in GIST because I just created a delay service for demo.  And I use $templateCache service for template.

Read More