Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular JS: using ng-switch and checking if file exists

i am looping through a list of things, and if a thing has an image i want to show it.

but if a thing does not have an image, i want to display default text:

<div ng-repeat="myThing in myThings>
  <div ng-switch on="{{myThing.img}}" >
    <span ng-switch-when="{{myThing.img}}">
      <img src="/img/myThings/{{myThing.id}}" />
    </span>
    <span ng-switch-default>No Image</span>
  </div>
</div>

this works and the default text is displayed.

however, the browser is also throwing an error trying to get an image which does not exist:

http://localhost:9000/img/myThings/%7B%7BmyThing.id%7D%7D 404 (Not Found)

is there a way to format this ng-switch function so that this error is not thrown?

like image 306
SeanPlusPlus Avatar asked Feb 16 '23 18:02

SeanPlusPlus


1 Answers

Use ng-src instead of src, this is from the doc:

Using Angular markup like {{hash}} in a src attribute doesn't work right: The browser will fetch from the URL with the literal text {{hash}} until Angular replaces the expression inside {{hash}}. The ngSrc directive solves this problem.

<img ng-src="/img/myThings/{{myThing.id}}" />
like image 131
zs2020 Avatar answered Feb 18 '23 09:02

zs2020