5

I have a best practice question regarding showing/hiding an ajax loading animation while I/O is being performed. Currently, I am handling the animation using the following code:

JS

app.controller('MyController', function($scope, Resource) {
    $scope.loading = true;
    Resource.query(function(response) {
        $scope.loading = false;
        $scope.items = response;
    });
});

HTML

<ul ng-controller="MyController">
    <div ng-if="loading">
        <img src="/assets/ajax-loader.gif">
    </div>
    <li ng-repeat="item in items">{{ item }}</li>
</ul>

Is this the best way to handle the showing/hiding of the ajax loader? I see some scalability issues as I start to add multiple modules and have to store a separate loading value for each.

1
  • 5
    I'm a fan of CSS only approach. You set the loading.gif as background of the container or item with a class that you toggle when you load the data. When it's loaded, then you remove the class. Commented Jan 15, 2014 at 21:31

2 Answers 2

3

Here are a few solutions:

https://github.com/chieffancypants/angular-loading-bar

https://github.com/zhoutuoy/ngRainbow

Some of these manipulate the css in a service. But the code is well documented as to why. I hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

1

The technique used to achieve this behavior is creating your own interceptor that will (as the title suggests) intercept any XHR requests.

More on this can be found over at the AngularJS documentation: http://code.angularjs.org/1.2.8/docs/api/ng.$http#description_interceptors

It has a pretty well documented example. You can also search stack overflow for a good approach to this. Be mindful that Response Interceptors (not to be confused with interceptors) are deprecated in the newer AngularJs versions.

Or of you want a all-in-one solution, you can check out one of the many open-source projects that calebboyd suggested.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.