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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With