3

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"}}'/>
TobiasW
  • 861
  • 3
  • 13
  • 36
  • whats not working ? are the images not present or can you make a fiddle – Susheel Singh Oct 10 '15 at 07: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 – TobiasW Oct 10 '15 at 07:22

1 Answers1

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="" >
Gaurav Sachan
  • 320
  • 1
  • 10
  • 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 :) – TobiasW Oct 10 '15 at 09:35
  • https://www.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). – TamusJRoyce Feb 18 '21 at 19:05
  • https://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. – TamusJRoyce Feb 18 '21 at 19:33