ngSrc path resolves to a 404, angular directive to fallback to as default

By: Ryan Wong at

Here’s the solution to 404 images.

HTML:

1
<img ng-src="{{something}}" err-src="/assets/images/defaultLogo.png" class="max-width"/>

Directive:

1
2
3
4
5
6
7
8
9
10
11
12
13
'use strict';

angular.module('app').directive('errSrc', function() {
return {
link: function(scope, element, attrs) {
element.bind('error', function() {
if (attrs.src != attrs.errSrc) {
attrs.$set('src', attrs.errSrc);
}
});
}
}
});