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

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

Html:

<img ng-src="https://stackoverflow.com/questions/16310298/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.

Leave a Comment