2017-12-20 11 views
0

オブジェクトリスト(profileList)にユーザーがいる場合はユーザーの画像を表示し、ない場合はdefaultProfile.pngとしてdefault/errorを表示します。ユーザが発見された({{item.userProfileは}}ヌルである)ng-repeatで無効なURLでng-srcを処理する方法

Iは、

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を取得していますエラー写真を表示することができる午前、

http://example.com/.jpg 500(内部サーバーエラー)をGET

http://example.com//.jpgを避けるには?

どうもありがとう

答えて

1

一つのアプローチは、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を示し、それ以外の場合はその逆のデフォルトを非表示にします。

+0

私は上記の方法を試しましたが、まだステータス500のエラーが発生しています。私のリストは$ scope.profileList = {fullName: "xxx"、userProfile:null}です。 userProfileをnull、string.emptyとして設定しようとしましたが、定義しませんでしたが、何も問題ありませんか?ありがとう – Ron

+0

'ng-show'を' ng-if'に変更しました。 – georgeawg

1

これは機能します。

NG-ショー

{{item.userProfile}}がnullかではないに関係なく実行されます。それを変更することにより

コードの下

が働いている

NG-場合:

:私のProfileListのは

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

ノート

どうもありがとう

2

userProfileが定義されていないときあなたの現在の問題がng-srcがまだ無効なURLにコンパイルされ、評価されています。それはitem.userProfileが利用可能でない限り、あなたは常にデフォルトの画像を取得することを保証します

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

A簡単な解決策は、三元使用して描画するかURLを決定する前userProfileをチェックすることです。

関連する問題