ChanandlerBong ChanandlerBong - 1 year ago 120
AngularJS Question

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="{{}}" ng-repeat="network in networks">
<td class="imgContainer">
<img ng-src="{{('assets/img/networkicons/'+network.actual+'.png') || 'assets/img/networkicons/default.png'}}"/>

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 Source

Interesting way to use ng-src. I haven't tested how that expression would be handled but I would suggest doing it a more stable way:

<img ng-src="{{ networkIcon }}" />

And in your controller:

$scope.networkIcon = network.actual ? 'assets/img/networkicons/' + network.actual + '.png' : 'assets/img/networkicons/default.png';

Edit: Just to clarify, I'm not suggesting the best way to do this is to bind the image source directly to the scope but rather to move the image fallback logic outside of the view. In my applications I often do it in the services that retrieve the data or on the server itself and send an image URL so the client only has to worry about a single property.

Edit to address repeater:

angular.forEach($scope.networks, function(network) {
  network.icon = network.actual ? 'assets/img/networkicons/' + network.actual + '.png' : 'assets/img/networkicons/default.png';

<tr ng-repeat="network in networks">
  <td><img ng-src="{{ network.icon }}" /></td>