Question

On angular, i'm looking to detect when an image is loaded after a change in the scope.

I have this :

<img ng-src="/uploads/screenshots/{{screenshot.imageURL}}" screenshotimageonload>

I know i can detect image loading by a directive like this :

angular.module('app').directive('screenshotimageonload', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
          element.bind("load", function () {
            console.log("Image loaded !");
          });
        }
    }
});

And detect a change in the scope like this :

angular.module('app').directive('screenshotimageonload', function () {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      scope.$watch('screenshot', function () {
        console.log("Image url change !");
      });
    }
  }
});

But i can't figure out, how bind both of them.

Was it helpful?

Solution

So, i found what i was looking for !

This fiddle help me a lot : http://jsfiddle.net/eyston/URrbN/

This is what i make :

angular.module('app').directive('screenshotimageonload', function () {
    return {
        restrict: 'A',

        // Bind the DOM events to the scope
        link: function (scope, element, attrs) {

            // Check when change scope occurs
            scope.$watch('screenshot', function () {
                if (scope.screenshot) {
                    console.log("New image url : " + scope.screenshot.imageURL);
                }
            });

            // When new image is loaded
            element.bind('load', function () {
                console.log("New image url is loaded ! " + scope.screenshot.imageURL);
            });
        }
    };
});

If this directive can help others ;)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top