Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing AJAX loading bars in AngularJS

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.

like image 511
user2066880 Avatar asked Oct 02 '22 20:10

user2066880


2 Answers

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.

like image 80
calebboyd Avatar answered Oct 13 '22 11:10

calebboyd


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.

like image 36
Michiel De Mey Avatar answered Oct 13 '22 10:10

Michiel De Mey