Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image loaded event in for ng-src in AngularJS

I have images looking like <img ng-src="dynamically inserted url"/>. When a single image is loaded, I need to apply iScroll refresh() method so that to make image scrollable.

What is the best way to know when an image is fully loaded to run some callback?

like image 741
Sergei Basharov Avatar asked Jul 26 '13 14:07

Sergei Basharov


4 Answers

Here is an example how to call image onload http://jsfiddle.net/2CsfZ/2/

Basic idea is create a directive and add it as attribute to img tag.

JS:

app.directive('imageonload', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('load', function() {
                alert('image is loaded');
            });
            element.bind('error', function(){
                alert('image could not be loaded');
            });
        }
    };
});

HTML:

 <img ng-src="{{src}}" imageonload />
like image 89
mikach Avatar answered Oct 13 '22 22:10

mikach


I modified this a little so that custom $scope methods can be called:

<img ng-src="{{src}}" imageonload="doThis()" />

The directive:

.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);
                });
            }
        };
    })

Hope someone finds it VERY useful. Thanks @mikach

The doThis() function would then be a $scope method

like image 41
Peter Avatar answered Oct 13 '22 21:10

Peter


@ Oleg Tikhonov: Just updated the previous code.. @ mikach Thanks..)

app.directive('imageonload', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
        element.bind('load', function() {
            alert('image is loaded');
        });
        element.bind('error', function(){
             alert('image could not be loaded');
        });
    }
  };
});
like image 9
Kailash Avatar answered Oct 13 '22 20:10

Kailash


My answer:

 var img = new Image();
 var imgUrl = "path_to_image.jpg";
 img.src = imgUrl;
 img.onload = function () {
      $scope.pic = img.src;
 }
like image 5
Rodrigo Andrade Avatar answered Oct 13 '22 22:10

Rodrigo Andrade