1

I've got a view that I load which contains a substantial number of images (between 100-200 typically), so this can take around 5 seconds to fully load / render, so I want to add a loading indicator during that time.

My problem is, I can't seem to find a reliable way of knowing when to present the view and hide the loading indicator. Previously, I'd used this piece of [jQuery] code to achieve this:

$(window).load(function() { $('.loading-notice').fadeOut(300, function () { $('.library-thumbnails').fadeIn(1000); }); });

Which worked great - however this isn't usable when loading a view in via Angular.js it seems.

I've got my Angular.js template and controller setup fine to do the fading in and out in the same style of which I did using jQuery, but I just can't detect when the images have all finished loading is all - I can only seem to detect when the JSON is returned from the server that will be used in the model.

EDIT I should have mentioned, I also tried using $viewContentLoaded as per below, however this is called before the images finish loading.

$scope.$on('$viewContentLoaded', function () { console.log('$viewContentLoaded'); });

  • 1
    `window.onload` doesn't work in Angular because the window doesn't reload, the content is populated dynamically. What you probably want instead is `$viewContentLoaded` – adeneo Dec 24 '14 at 23:45
  • @adeneo sorry, I should have mentioned I had tried that (see edited post now), thanks for the suggestion though –  Dec 24 '14 at 23:53
  • Hey @rastating, did you try my response? – Adam Dec 28 '14 at 21:41

1 Answers1

0

Resource: ngLoading

A good friend of mine at Hack Reactor (Mason Hargrove) created an Angular directive called ngLoading that you can drop in for purposes just like this.

Here's what it does:

ngLoading will listen to any http request made from your application and show the animation, when your application recieves the http response it will remove the animation.

Step-by-Step

  1. Install ngLoading:

    bower install ng-loading --save
    
  2. Inject ngLoading as a dependency to your main module:

    angular.module('myApp', ['ngLoading']);
    
  3. (Optional) If the images are not rendering quickly-enough to the template after the $http request is done, you could continue the loading screen (hacky and probably unnecessary):

    .controller('MyController', function(Interceptor, $timeout) {
      //trigger the loading screen to start
      Interceptor.start();
    
      // Give the images time, 4 seconds, to render
      $timeout(Interceptor.end, 4000)
    });
    

Result

While the images load from the server, the loader graphic will automatically display. It will stop when the $http request is done.

Futher Reading

Here's an interesting discussion for an Angular feature request, asking for "a way to detect if Angular finished rendering of HTML DOM." They generally suggest the use of $timeout as a workaround.

Adam
  • 2,027
  • 1
  • 16
  • 27