Ben
Ben

Reputation: 16699

Dealing with image not found

In AngularJS, how can I load a different image, if the one specified at first could not be found? In the case at hand, I have a slug, and don't know what the file extension will be. It could e.g. be png, jpg, svg.

What I want to do is:

<img ng-src="images/{{slug}}" />

And then I want it to go and check

images/{{slug}}.png
images/{{slug}}.jpg
images/{{slug}}.svg

until it has found a file that exists.

Is there a function that fires if an image could not be loaded?

Upvotes: 0

Views: 458

Answers (2)

sylwester
sylwester

Reputation: 16508

Hi Ben you create directive like that http://plnkr.co/edit/Bp47O0sqyO10mZGDiVGh?p=preview

FUNCTION TO CHECK IF IMAGE EXIST:

function imageExists(url, callback) {
  var img = new Image();
  img.onload = function() {
    callback(true);
  };
  img.onerror = function() {
    callback(false);
  };
  img.src = url;
}

DIRECTIVE:

angular.module('app').directive('fallbackSrc', [fallbackSrc]);

    function fallbackSrc() {

      var fallbackSrc = {
        scope: {
          fsrc: '@'

        },
        link: function postLink(scope, elem, attr) {
          var ext = ['.png', '.svg', '.jpg'];

          existingImage = ext.some(function(extension ) {
            var imageUrl = scope.fsrc + extension;

            imageExists(imageUrl, function(exists) {
              if (exists) {
                angular.element(elem).attr("src", imageUrl);
                return true;
}

            });

          });

        }
      };
      return fallbackSrc;


    };

HTML:

 <img fallback-src fsrc="http://www.google.com/images/srpr/nav_logo14" />

Upvotes: 1

Dalorzo
Dalorzo

Reputation: 20024

Try this:

<object data="images/{{slug}}.png" type="image/png">
   <img ng-src="images/{{slug }}" />
 </object>

Upvotes: 0

Related Questions