Angularjs fallback image directive

Using fallback image with <img> tag is common scenario to show a default image if the original image is not loaded. In angular you can achieve this by creating a fallback directive like below,

angular.module('fallback',[]).directive('fallbackSrc', function () {
    return{
        link: function postLink(scope, element, attrs) {
            element.bind('error', function () {
                angular.element(this).attr("src", attrs.fallbackSrc);
            });
        }
    }
});
<img ng-src="{{url}}" fall-back-src="default.jpg"/>

What it does is listen for the onError event of the original image, then replace it with the default image if it fails to load.

But drawback of this directive is that it will show broken image until the original image’s onError method is called, then it will assign default image source. To overcome this, I have created  the below directive,

angular.module('fallback', []).directive('actualSrc', function () {
    return{
        link: function postLink(scope, element, attrs) {
            attrs.$observe('actualSrc', function(newVal, oldVal){
                 if(newVal != undefined){
                     var img = new Image();
                     img.src = attrs.actualSrc;
                     angular.element(img).bind('load', function () {
                         element.attr("src", attrs.actualSrc);
                     });
                 }
            });

        }
    }
});
<img actual-src="{{url}}" ng-src="default.jpg"/>

This will assign the default image as source and checks for the load event of original image, then substitutes it if the image is loaded. By using this user won’t see broken image at all.

Find the full directive in this Git repository

Hope it helps some one.

Related Posts

Angularjs directive to show loader for image

Here you go for the directive to show loader for images in your angularjs application. Inject the module “sesu.imageloader” in your main app module and start using…

jQuery plugin for expanding search bar

I have created a jQuery plugin to handle expand and close functionality of searchbar. This would help some to minimize their work, since it is straight forward…

Javascript Resize Image Proportionally and Clipping

Setting height and width to an image is a general scenario in web development. We need to take in account that image shouldn’t get stretched, it should…

This Post Has One Comment

Leave a Reply

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