1

I have to following directive that I am trying to set an onload listener for the img tag. Inside that link function I programmatically generate the img src.

angular.module('test', [])
.directive('imgTest', function() {
  return {
    restrict: 'A',
    template: '<img ng-src="{{imgSrc}}"></img>',
      link: function(scope, elem) {
      elem.on('load', function() {
        console.log('image loaded');
      });

      scope.imgSrc = "someurl?token=" + getAccessToken();  
    }
  };
});

However the onload function is not firing. Please go easy, I am sure I am doing something really stupid :)

lostintranslation
  • 23,756
  • 50
  • 159
  • 262

2 Answers2

1

"elem" is not the image. If you use your directive like the following,

<div img-test />

elem is the "div" instead of the image

user1111
  • 1,840
  • 2
  • 14
  • 18
0

elem.on('load') is a jQuery-style event listener. It doesn't look like you have a jQuery object as elem there - it came straight from Angular. So try:

$(elem).on('load', function () {})

or

elem.addEventListener('load', function() {});
Seth
  • 10,198
  • 10
  • 45
  • 68
Jack Guy
  • 8,346
  • 8
  • 55
  • 86
  • Thanks @Harangue. Still not getting the load event. My image is indeed loading as I can see it on the page. – lostintranslation Jun 24 '16 at 16:53
  • @lostintranslation I'm also pretty sure you're supposed to set "src" before the load listener. Not sure if that'll make a difference. – Jack Guy Jun 24 '16 at 16:59
  • always thought it was best practice to setup the listener before triggering the event that might fire the listener. Either way though, load even is still not firing. – lostintranslation Jun 24 '16 at 17:01
  • @lostintranslation Hmm I guess my only other suspicion is that it's a weird behavior of template directives. Is there any way you can switch to an attribute-based directive, like http://stackoverflow.com/a/26781900/1008741 – Jack Guy Jun 24 '16 at 17:15