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'}}"/>
asked Feb 3, 2018 at 22:57

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.

answered Feb 4, 2018 at 4:25
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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.