Search code examples
angularjshtml

Check if img-src exists with angular


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"}}'/>

Solution

  • 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="" >