MaxPower
MaxPower

Reputation: 871

onload image event in AngularJS component

I am using an angular 1.5 component as defined below.

ngModule.component('devStudioImage', {
    template: '<img id= "{{$ctrl.imageName}}" ng-src="{{$ctrl.source}}"/>',
    controller: Controller,
    bindings: {
        imageName: '@',
        imageHeight: '<',
        imageWidth: '<',
        imageDescription: '<?',
        imageLoaded: '&'
    }
});

I want to bind a load event as well for when the image has been loaded, but onload does not seem to work, and every other solution I seem to find involves making a directive.

Is there a way to capture that load event in this component, or if I have to use a directive, how can I use the same instance of the controller for my component?

Edit:

I ended up doing this. I think it's ugly, and feels...dirty, but it works.

I added a directive in addition to the component above, that applies to the parent scope a variable for an ng-show.

ngModule.directive('imageOnLoad', function() {
    return {
        restrict: 'A',
        link: function (scope, element) {
            element.bind('load', function() {
                scope.$parent.$ctrl.loaded = true;
                scope.$parent.$apply();
            });

        }
    }
})

Upvotes: 1

Views: 1427

Answers (3)

Shabbir Hussain
Shabbir Hussain

Reputation: 56

You can try this in your controller:

var element = $element.find('imgID');
    element.on('load', function() {
    alert("image is loaded");
});

First get the image element and then attach load event to it.

Upvotes: 1

sookool99
sookool99

Reputation: 262

You should be using a directive for this. However if you really don't want to do that, Since you are using Angular you already have jquery. Jquery has a load function.

The .load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.

the documentation can be found here: https://api.jquery.com/load-event/

Upvotes: 0

A.Sharma
A.Sharma

Reputation: 2799

For something like this, I would use a directive as opposed to a component. Directly from the AngularJS documentation:

When not to use Components:

-for directives that rely on DOM manipulation, adding event listeners etc, because the compile and link functions are unavailable

Upvotes: 1

Related Questions