Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting an image is fully loaded from a directive, where the directive is not applied to the image element

there are many examples in SO on how we can use an angular directive to know when an image is loaded. The examples describe a directive that is directly applied to the img element like so:

<img ng-src="myimage.jpg" my-great-directive />

And then in the directive "my-great-directive"

we can do an:

element.bind("load" , function(e){ }

And i works great.

However, what if the construct is like this:

<div my-great-directive>
  <img ng-src="myimage.jpg" />
</div>

Within my-great-directive, how do I bind to the inside image loaded event?

This is not really a theoretical problem for me. I am using a 3rd party slider called angular-carousel-slider that wraps around like so:

<ul rn-carousel  rn-carousel-buffered
                    rn-carousel-index="mycarousel.index"
                    rn-carousel-auto-slide="0.3" rn-carousel-pause-on-hover >
   <li ng-repeat="slide in slides">
       <img ng-src="{{eventBasePath}}{{slide.img}}?rand={{rand}}"/>
  </li>
</ul>

I'm trying to modify its code so that it does not slide to the next image unless the current image is fully loaded (to avoid the situation of a fast slider half loading images and moving to the next). I'm stuck on how I can trap this image loaded event inside the directive. Doing element.bind("load") does not work as the directive is not applied to the image element.

Thank you!

like image 974
user1361529 Avatar asked Jul 28 '15 00:07

user1361529


1 Answers

Check this working demo: JSFiddle

Use anguler.element to find the img element and bind the event.

In your directive, it should be element.find('img').

angular.module('Joy', [])
    .directive('hello', [function () {
    return {
        restrict: 'A',
        link: function (scope, ele) {
            var img = ele.find('img');
            console.log(img);
            img.bind('load', function () {
                console.log('img is loaded');
            });
        }
    };
}]);

HTML:

<div ng-app="Joy">
    <div hello>
        <img ng-src="https://www.google.com.hk/images/srpr/logo11w.png">
    </div>
</div>

Update 1

If use ng-repeat, add a $timeout to wait for ng-repeat finishes first. Check working demo: JSFiddle.

Note: this demo is loading a very large image. After the image is loaded, the text img is loaded will be shown.

Update 2

If the event binding is not working, try native image.onload binding (or oncomplete to find images cached). Working demo: JSFiddle.

like image 64
Joy Avatar answered Oct 03 '22 06:10

Joy