Angular JS: using ng-switch and checking file availability

I iterate over the list of things, and if the thing has an image that I want to display.

but if the thing has no image, I want to display the 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 also throws an error trying to get an image that 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 selected?

+4
source share
1 answer

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

Using Angular markup like {{hash}} in the src attribute does not work correctly: the browser will retrieve {{hash}} from the URL with the literal text until Angular replaces the expression inside {{hash}}. The ngSrc directive solves this problem.

 <img ng-src="/img/myThings/{{myThing.id}}" /> 
+8
source

Source: https://habr.com/ru/post/1494127/


All Articles