Conditionally change img src based on model data

I want to present the model data as different images using Angular, but there are some problems finding the β€œright” way to do this. Angular APIs in expressions say conditional expressions are not allowed ...

Simplifying simplification, model data is retrieved via AJAX and shows the status of each interface on the 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 values ​​from the model, I would like to show a suitable image. Something after 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 change the controller to return image urls based on the actual model data, but this seems to violate the separation of model and view, no?

This SO publication suggested using the directive to change the source of bg-img. But then we went back to placing the URLs in JS, not in the template ...

All suggestions are appreciated. Thank you

sorry for any typos

+62
angularjs
Dec 22 '12 at 2:50
source share
4 answers

Instead of src you need ng-src .

AngularJS Views Support Binary Operators

 condition && true || false 

So, the img tag will look like this:

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

Note : quotes are important here (ie "green-checkmark.png"). This will not work without quotes.

plunker here (open tools for viewing finished HTML)

+157
Dec 22
source share

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 probably be better / easier if you have more than two images.

+30
Dec 22
source share

Another way.

 <img ng-src="{{!video.playing ? 'img/icons/play-rounded-button-outline.svg' : 'img/icons/pause-thin-rounded-button.svg'}}" /> 
+14
Jun 21 '16 at 12:39
source share
 <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> 
+4
Jan 6 '15 at 17:28
source share



All Articles