ON LOAD sync with ANGULAR JS directive

I am learning directives with angular js. I am trying to create a simple piece of code to display a spinner when loading large images.

This is almost normal, but when I load multiple images, I am surprised that all ONLOADs are started at once when all images are finished. I would like them to run independently every time the image ends.

I think something needs to be specified about synchronization to get rid of this, but what?

Here's the code.

app.
directive(
  'imgPreload', [

    function() {

      function preload(scope, element) {

        element.on('load', function() {
          // Image loaded: make it visible
          element.removeClass('image-hide');
          // Delete spinner
          scope.spinner.remove();
        });

        scope.$watch('ngSrc', function() {
          // Make image invisible while loading
          element.addClass('image-hide');
          // Get spinner image from HTML page
          var preloadImage = angular.element(document.querySelector('#preload-image'))[0];
          // Create a new image to display instead of real image
          // and affect it spinner src
          scope.spinner = new Image();
          scope.spinner.src = preloadImage.src;
          // Put spinner in DOM instead of (side to side) real image.
          // Parent image is DIV. It just to know where to insert the spinner.
          element.parent().append(scope.spinner);
        });
      }

      return {
        restrict: 'A',
        scope: {},
        link: preload
      };
    }
  ]
);
      

.image-hide {
  display: none;
}
      

<!-- Spinner image for preloader (image is hidden: just to get the src when needed) -->
<img id="preload-image" class="image-hide" src="spinner.gif" />

<!-- 2 images are loaded, a small and a big (use of div is explained on JS) -->
<div><img src="petite_image.jpg" img-preload/></div>
<div><img src="grosse_image.jpg" img-preload/></div>
      

Run codeHide result


+3


source to share





All Articles