4

I want a simple determination if the image source exists or not, so that I can replace the image with a default image. Best case would be if this would be possible in pure html maybe with "ng-if" or something like this.

<img ng-if="../images/{{id}}.png"  src="../images/{{id}}.png">

This code obviously doesn't work, but I think it shows what I want.

EDIT:

New Code I got, which could work in my opinion, but doesn't work:

<img ng-src='{{ "../images/{{id}}.png" || "../images/img.png" }}'/>

Debugger says something about wrong quotes in this case.

EDIT:

I think the second solution works, there is just some bug in this part:

<img ng-src='{{"../images/{{id}}.png"}}'/>

This part works:

<img ng-src='{{"../images/img.png"}}'/>
2
  • whats not working ? are the images not present or can you make a fiddle Commented Oct 10, 2015 at 7:12
  • The Expression doesn't work, it doesn't show the image if the image is present neither if it isn't present. I try to create a fiddle but I'm not sure how that works with angular Commented Oct 10, 2015 at 7:22

2 Answers 2

9

You can use onerror, here is a demo.

<img ng-src="http://experenzia.com/images/431f5cfa87f2faf9317ccc89e980dcca/431f5cfa87f2faf9317ccc89e980dcca_t.jpg" onerror="this.src='http://www.experenzia.com/assets/images/planner/no-image-back.png'" alt="" >
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I wanted it as easy as possible, so this is the best solution for me. Maybe for some others the other solution with the directive is the best :)
caniuse.com/mdn-html_elements_img_onerror - says this is deprecated. This also doesn't work for IE11 (important if you have to provide commercial support for it).
stackoverflow.com/a/59366589/458321 - best practice is to set this up in a script, not as an attribute. The attribute is deprecated, not the event.
0

For anyone looking for a code solution ...

imageExists (url) {
    return fetch(url, { mode: 'no-cors'}).then(_ => {
      return true;
    })
    .catch(e => {
      return false;
    });
  }

Note this returns a promise. Also note, that the no-cors will enable you to bypass CORS errors from servers with string origin-control set.

Call it like so...

let imageUrl = "https://img.youtube.com/vi/"+ [some video id] +"/0.jpg";
let imageExists = await this.imageExists(imageUrl);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.