gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 05:12:35 25 4
gpt4 key购买 nike

我正在遍历事物列表,如果事物有图像,我想显示它。

但是如果一个东西没有图像,我想显示默认文本:

<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>

这有效并显示默认文本。

但是,浏览器在尝试获取不存在的图像时也会抛出错误:

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

有没有办法格式化这个 ng-switch 函数,这样就不会抛出这个错误?

最佳答案

使用ng-src而不是 src,这是来自文档:

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

关于javascript - Angular JS : using ng-switch and checking if file exists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17932628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com