Skip to content

Instantly share code, notes, and snippets.

@dprea
Created January 10, 2016 02:21
Show Gist options
  • Save dprea/1cd27241db661818e509 to your computer and use it in GitHub Desktop.
Save dprea/1cd27241db661818e509 to your computer and use it in GitHub Desktop.
Angular ng-src onerror such as image resolves to a broken src
/**
* First is the Angular Directive method of solving.
* Second is the inline onerror fix that results in a default image.
* SOURCE: http://stackoverflow.com/questions/27549134/angularjs-ng-src-condition-if-not-found-via-url
*/
var myApp = angular.module('myApp',[]);
myApp.directive('onErrorSrc', function() {
return {
link: function(scope, element, attrs) {
element.bind('error', function() {
if (attrs.src != attrs.onErrorSrc) {
attrs.$set('src', attrs.onErrorSrc);
}
});
}
}
});
<img ng-src="wrongUrl.png" on-error-src="http://google.com/favicon.ico"/>
// Angular inline onerror fix that results in a default image.
<img ng-src="{{ yourImageCurrentScopeVar }}" onerror="this.src='img/default-image-when-occur-a-error.png'"/>
@bryanmorganoverbey
Copy link

Yes. Line 25 was so simple and resolved my issue with images not loading sometimes.

@emilyandyu
Copy link

Template parse errors:
Can't bind to 'ng-src' since it isn't a known property of 'img'.
How can I fix it?

@SuperStar518
Copy link

good solution.

@vard3000
Copy link

I needed to load an image potentially from two different folders, if it did not exist in the first folder, then angular would look for that same image in the second folder. Simple directive and very helpful. Thanks for sharing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment