如何在 ng-repeat 中处理无效 url 的 ng-src

how to deal with ng-src with invalid url in ng-repeat

如果我的对象列表(profileList)中有一个用户,我想显示一个用户的图片,当没有找到用户时default/error显示为defaultProfile.png({{item.userProfile}} 为空)

我搜索过类似的方法,例如

angularjs: ng-src equivalent for background-image:url(…)

empty ng-src doesn't update image

我解决这个问题的方法是:

<div ng-repeat="item in profileList">
    <div>
     <img src='assets/img/defaultProfile.png' data-ng-src="http://example.com/{{item.userProfile}}.jpg" onerror="this.src='assets/img/defaultProfile.png'" />
    </div>
<div>

我可以显示错误照片,但我仍然收到错误 500,

GET http://example.com/.jpg 500 (INTERNAL SERVER ERROR)

如何避免得到http://example.com//.jpg

非常感谢

一种方法是使用 ng-ifng-hide:

<div ng-repeat="item in profileList">
    <div>
     <img ng-if="item.userProfile" 
          data-ng-src="http://example.com/{{item.userProfile}}.jpg" />
     <img ng-hide="item.userProfile" 
          src="assets/img/defaultProfile.png" />
    </div>
<div>

item.userProfile 存在时,显示 ng-src 并隐藏默认值,否则反之亦然。

有效。

ng-show

将 运行 无论 {{item.userProfile}} 是否为 null。

通过将其更改为

ng-if

以下代码有效:

<div ng-repeat="item in profileList">
<div>
 <img ng-if="item.userProfile" 
      data-ng-src="http://example.com/{{item.userProfile}}.jpg" />
 <img ng-if="item.userProfile == null" 
      src="assets/img/defaultProfile.png" />
</div>

注意我的个人资料列表是:

$scope.profileList = {userProfile = null}

非常感谢

您当前的问题是当 userProfile 未定义时,ng-src 仍被编译并评估为无效的 url。

一个简单的解决方案是使用三进制并在决定 url 应该被渲染之前检查 userProfile

 <img ng-src="{{ item.userProfile ? 'http://example.com/' + item.userProfile + '.jpg'}} : 'assets/img/defaultProfile.png'" />

除非 item.userProfile 可用,否则它将保证您将始终获取默认图像。