Reputation: 891
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"}}'/>
Upvotes: 4
Views: 12554
Reputation: 2258
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);
Upvotes: 0
Reputation: 320
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="" >
Upvotes: 9