0

I would like to show the picture of a user if there is a user in my object list (profileList), and default/error as defaultProfile.png when no user is found ({{item.userProfile}} is null)

I have searched for similar approaches such as

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

and

empty ng-src doesn't update image

My approach to this problem is:

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

I am able to show error photo however I am still getting error 500,

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

How to avoid getting http://example.com//.jpg?

Thanks a lot

Ron
  • 67
  • 1
  • 10

3 Answers3

2

Your current issue is ng-src is still compiled and evaluated to an invalid url when userProfile is undefined.

A simple solution is to use ternary and check for userProfile before deciding with url should be rendered:

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

It will guarantee that you will always fetch the default image unless item.userProfile is available.

Thai Duong Tran
  • 2,453
  • 12
  • 15
1

One approach is to use ng-if and ng-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>

When item.userProfile exists, show the ng-src and hide the default otherwise vice versa.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
  • I have tried the method as above but still getting status 500 error. My list is $scope.profileList = {fullName:"xxx", userProfile:null }. I have tried to set userProfile as null, string.empty and not defining but none works, any idea? Thanks – Ron Dec 20 '17 at 02:17
1

It works.

ng-show

will run no matter {{item.userProfile}} is null or not.

By changing it to

ng-if

Below code is working:

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

note that my profileList is:

$scope.profileList = {userProfile = null}

Thanks a lot

Ron
  • 67
  • 1
  • 10