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.
Thank you so much Subhash.. 🙂