if a ngSrc path resolves to a 404, is there a way to fallback to a default?

will_hardin picture will_hardin · May 1, 2013 · Viewed 81.7k times · Source

The application I'm building requires my user to set 4 pieces of information before this image even has a chance of loading. This image is the center-piece of the application, so the broken image link makes it look like the whole thing is borked. I'd like to have another image take its place on a 404.

Any ideas? I'd like to avoid writing a custom directive for this.

I was surprised that I couldn't find a similar question, especially when the first question in the docs is the same one!

http://docs.angularjs.org/api/ng.directive:ngSrc

Answer

Jason Goemaat picture Jason Goemaat · Jun 15, 2013

It's a pretty simple directive to watch for an error loading an image and to replace the src. (Plunker)

Html:

<img ng-src="smiley.png" err-src="http://google.com/favicon.ico" />

Javascript:

var app = angular.module("MyApp", []);

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

If you want to display the error image when ngSrc is blank you can add this (Plunker):

attrs.$observe('ngSrc', function(value) {
  if (!value && attrs.errSrc) {
    attrs.$set('src', attrs.errSrc);
  }
});

The problem is that ngSrc doesn't update the src attribute if the value is blank.