0

I need to put a default image into img element.

If I get an error loading the image or the image is null/undefined I´d like to put a default image

I have the next markup:

//controller

$scope.img_default="//ssl.gstatic.com/accounts/ui/avatar_2x.png"

//markup

<img  onerror="this.src='+{{img_default}}+'"
                    class="drop-box-filled-totem img-responsive"  
                    style="width:100%; height: 100%; max-height: 350px;"
                    ng-src="{{mobileCart||img_default}}"/>

But it doesn´t work.

If I use the image url right into html, it works as below.

Is there a way to make it work using data bind by controller?

<img  onerror="this.src='//ssl.gstatic.com/accounts/ui/avatar_2x.png'"
                    class="drop-box-filled-totem img-responsive"  
                    style="width:100%; height: 100%; max-height: 350px;"
                    ng-src="{{mobileCart||'//ssl.gstatic.com/accounts/ui/avatar_2x.png'}}"/>

1 Answer 1

2

Below code works fine for me

<img  class="drop-box-filled-totem img-responsive"  
      style="width:100%; height: 100%; max-height: 350px;"
      ng-src="{{mobileCart||img_default}}"/>

Here is the plunker, I think adding onerror attr is not what you should do because it is not informed about the angularjs $digest cycle.

From my understanding, on onerror you add some event which is triggered. you can achieve the same check in the controller itself. Just take into account that angularjs has its own digest cycle which should be taken care of.

Sign up to request clarification or add additional context in comments.

1 Comment

OK, My problem is really in "onerror". I managed to do it with a function

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.