Skip to content

Instantly share code, notes, and snippets.

@kiub
Last active August 29, 2015 14:25
Show Gist options
  • Save kiub/a6f689d43db20086e4e8 to your computer and use it in GitHub Desktop.
Save kiub/a6f689d43db20086e4e8 to your computer and use it in GitHub Desktop.
Img directive to render a default image if ngSrc path resolves to a 404
// source code from:
// http://stackoverflow.com/questions/16310298/if-a-ngsrc-path-resolves-to-a-404-is-there-a-way-to-fallback-to-a-default
app.directive('img', function () {
return {
restrict: 'E',
link: function (scope, element, attrs) {
// show an image-missing image
element.bind('error', function () {
var w = element.width();
var h = element.height();
// using 20 here because it seems even a missing image will have ~18px width
// after this error function has been called
if (w <= 20) { w = 100; }
if (h <= 20) { h = 100; }
var url = 'http://placehold.it/' + w + 'x' + h + '/cccccc/ffffff&text=Image+not+found'; // or change for a default image
element.prop('src', url);
// element.css('border', 'double 3px #cccccc'); optionally we can add custom styles, etc
});
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment