Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally change img src based on model data

Tags:

angularjs

I want to represent model data as different images using Angular but having some trouble finding the "right" way to do it. The Angular API docs on expressions say that conditional expressions are not allowed...

Simplifying a lot, the model data is fetched via AJAX and shows you the status of each interface on a router. Something like:

$scope.interfaces = ["UP", "DOWN", "UP", "UP", "UP", "UP", "DOWN"]

So, in Angular, we can display the state of each interface with something like:

<ul>
  <li ng-repeat=interface in interfaces>{{interface}}
</ul>

BUT - Instead of the values from the model, I'd like to show a suitable image. Something following this general idea.

<ul>
  <li ng-repeat=interface in interfaces>
    {{if interface=="UP"}}
       <img src='green-checkmark.png'>
    {{else}}
       <img src='big-black-X.png'>
    {{/if}}
</ul>

(I think Ember supports this type of construct)

Of course, I could modify the controller to return image URLs based on the actual model data but that seems to violate the separation of model and view, no?

This SO Posting suggested using a directive to change the bg-img source. But then we are back to putting URLs in the JS not the template...

All suggestions appreciated. Thanks.

please excuse any typos

like image 382
Danny Avatar asked Dec 22 '12 02:12

Danny


4 Answers

Instead of src you need ng-src.

AngularJS views support binary operators

condition && true || false

So your img tag would look like this

<img ng-src="{{interface == 'UP' && 'green-checkmark.png' || 'big-black-X.png'}}"/>

Note : the quotes (ie 'green-checkmark.png') are important here. It won't work without quotes.

plunker here (open dev tools to see the produced HTML)

like image 61
jaime Avatar answered Oct 15 '22 17:10

jaime


Another alternative (other than binary operators suggested by @jm-) is to use ng-switch:

<span ng-switch on="interface">
   <img ng-switch-when="UP" src='green-checkmark.png'>
   <img ng-switch-default   src='big-black-X.png'>
</span>

ng-switch will likely be better/easier if you have more than two images.

like image 20
Mark Rajcok Avatar answered Oct 15 '22 17:10

Mark Rajcok


Another way ..

<img ng-src="{{!video.playing ? 'img/icons/play-rounded-button-outline.svg' : 'img/icons/pause-thin-rounded-button.svg'}}" />
like image 40
pkdkk Avatar answered Oct 15 '22 16:10

pkdkk


<ul>
  <li ng-repeat=interface in interfaces>
       <img src='green-checkmark.png' ng-show="interface=='UP'" />
       <img src='big-black-X.png' ng-show="interface=='DOWN'" />
  </li>
</ul>
like image 27
mia Avatar answered Oct 15 '22 16:10

mia