0

I have been using Angular for a while now and I am always using ngShow, ngHide, ngIf, etc.

A problem I have always encountered when using these directives to show and hide images is the one second immediately after the directive sets to true or false and the images haven't loaded yet. The page just hangs blank for a moment and then the images pop into existence in little chunks.

Is there some way to track if all the images in a view have been retrieved from the server and are finished rendering? That way I could employ a loading spinner or something until all the images are 100% ready.

030
  • 10,842
  • 12
  • 78
  • 123
aadu
  • 3,196
  • 9
  • 39
  • 62
  • 1
    Maybe this could be of help: http://stackoverflow.com/questions/17884399/image-loaded-event-in-for-ng-src-in-angularjs – valepu Nov 25 '15 at 13:25

1 Answers1

0

If you want to execute some code, when an image is fully loaded, you can use an custom directive in AngularJS, something like:

app.module['myApp'].directive('imageOnload', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('load', function() {
                // call the function that was passed
                scope.$apply(attrs.imageOnload);


            });
        }
    };
});

Usage:

<img ng-src="src" image-onload="customFonction()" />
aitnasser
  • 1,216
  • 1
  • 9
  • 23
  • So if I was loading a lot of images, say 50+, in an ng-repeat or something, would this directive be scalable? – aadu Nov 25 '15 at 13:57
  • no is not, it would create 50 events which would stay active after the loading. You should be using .one instead of .bind, so that the events would be destroyed after being called once. Also bind is deprecated and you should use ".on" instead – valepu Nov 25 '15 at 14:07
  • This response can help you:: http://stackoverflow.com/questions/18547186/bind-event-in-a-directive-doesnt-work-if-the-directive-is-in-a-ng-repeat-loop – aitnasser Nov 25 '15 at 14:55