Fallback (default) image using Angular JS ng-src

nikjohn picture nikjohn · Jul 7, 2014 · Viewed 29.9k times · Source

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.

Answer

kudlajz picture kudlajz · Sep 22, 2015

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.