1

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

        }
    }
})

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I thought this would be the case, I was just wondering if there might be some other solution.
1

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.

Comments

0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.