Blog on software engineering
AngularJS onload image custom directive

AngularJS onload image custom directive

If you want to execute some code, when an image is fully loaded, you can use an custom directive in AngularJS, something like:

(function () {
    /// <summary>
    /// Bind to onload event, e.g. onload image.
    /// </summary>
    "use strict";

    function directive() {
        
        function link($scope, $element, attrs) {

            $element.bind('load', function () {

                $scope.options.load($element[0]);
                
            });

        }

        return {
            restrict: "A",
            scope: {
                options: "=htoOnload"
            },
            link: link
        };
    }

    angular
        .module("hto")
        .directive("htoOnload", [directive]);

}());

Usage:

<img id="locationImage" ng-src="{{ app.locationImageUrl }}" hto-onload="{ load: app.onLocationImageLoad }" />

The $scope contains an object “app” containing a function “onLocationImageLoad”.

The image is dynamically loaded by AngularJS, when the app.locationImageUrl changes.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.