How do I have AngularJS show a loading spinner until the data has finished loading?
If my controller has $scope.items = [{name: "One"}]
set up statically, and an AJAX loader which populates $scope.items[0]['lateLoader'] = "Hello"
, I'd like the spinner to show until the AJAX load is complete, and then populate the bound span with the retrieved data.
<ul ng-repeat="item in items"> <li> <p>Always present: {{item.name}}</p> <p>Loads later: <span ng-bind="item.lateLoader"><i class="icon icon-refresh icon-spin"></i></span></p> </li> </ul>
This code populates the bound span immediately, and as item.lateLoader
is empty the spinner is replaced with nothing.
How should I do this cleanly?
I would create a custom directive as per the other answer, but here is how you could do it without the directive which might be a good idea to learn before getting into more complex functionality.. A couple things to note:
Demo: http://plnkr.co/edit/4XZJqnIpie0ucMNN6egy?p=preview
View:
<ul > <li ng-repeat="item in items"> <p>Always present: {{item.name}}</p> <p>Loads later: {{item.lateLoader}} <i ng-hide="item.lateLoader" class="icon icon-refresh icon-spin">loading image i don't have</i></p> </li> </ul>
Controller:
app.controller('MainCtrl', function($scope) { $scope.name = 'World'; $scope.items = [{name: "One"}]; setTimeout(function() { $scope.$apply(function() { $scope.items[0].lateLoader = 'i just loaded'; }); }, 1000); });
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