Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fallback (default) image using Angular JS ng-src

I'm trying to set an image source using data returned from a modal. This is inside an ng-repeat loop:

<div id="divNetworkGrid">
    <div id="{{network.id}}" ng-repeat="network in networks">
        <span>
            <table>
                <tr>
                    <td class="imgContainer">
                        <img ng-src="{{ ('assets/img/networkicons/'+ network.actual + '.png') || 
                                         'assets/img/networkicons/default.png' }}"/>
                    </td>
                </tr>
            </table>
        </span>
    </div>
</div>

As is apparent, I want to populate default.png when the network.actual model property is returned as null. But my code is not picking up the default image, though the first image is coming up fine when available.

I'm sure this is some syntax issue, but cant figure out what's wrong.

like image 307
nikjohn Avatar asked Jul 07 '14 15:07

nikjohn


2 Answers

I have just found out, that you can use both ng-src and src on an img tag and if ng-src fails (variable used does not exists etc.), it will automatically fallback to src attribute.

like image 55
kudlajz Avatar answered Oct 16 '22 03:10

kudlajz


What I imagine is happening is the src is returning a 404 even if network.actual is null. For example, first value:

('assets/img/networkicons/'+network.actual+'.png')

is evaluating to a 404 src URL, something like ('assets/img/networkicons/null.png'). So in the OR selection, it's truth-y, but the resource is 404. In that case, you can set the fallback via onError with something like:

<img ng-src="{{('assets/img/networkicons/'+network.actual+'.png')}}" onerror="this.src='assets/img/networkicons/default.png'" />

CodePen to demo use cases - http://codepen.io/jpost-vlocity/pen/zqqerL

like image 32
jpostdesign Avatar answered Oct 16 '22 04:10

jpostdesign