B5-NDDT B5-NDDT - 2 months ago 22
Ajax Question

How to add Spinner-Gif before ng-include is fully loaded

I have a div-layer which dynamically loads html-partials from the server. The template variable is changed when a link in the navigation is clicked.

<div id="ajaxwrapper" ng-include="template">
</div>


This works fine. But the templates need a short time to load and during that time the user doesn't get any kind of response. Thats why I want to display a spinner until the template is load. Sadly I don't know how.

My links look something like this:

<a ng-click="navi($event)" href="www.someurl.de">Text</a>


The navi-function looks like this:

$scope.navi = function (elem) {
elem.preventDefault();
var urlstring = "";
if (typeof elem.target.href !== 'undefined') {
urlstring = elem.target.href;
$location.path(elem.target.pathname).search({ knt: $scope.aktuellesVertragskonto.nr });;
} else {
urlstring = elem.target.baseURI
$location.path("/");
}
$scope.template = $location.absUrl();
};


I need some pointers on how to implement a spinner. Thank you :)

The spinner-template would look like this:

<script type="text/ng-template" id="loader">
<div class="text-center">
<img src="~/images/spinner/ajax-loader.gif" /><br />
Loading
</div>



Answer

The ng-include directive includes an onload expression (reference), so you can do something like this:

<div id="ajaxwrapper" 
     ng-show="loaded"
     ng-include="template" onload="loaded = true">
</div>

<div class="text-center"
     ng-hide="loaded">
    <img src="~/images/spinner/ajax-loader.gif" /><br />
    Loading
</div>