Danny Danny - 1 year ago 73
AngularJS Question

Conditionally change img src based on model data

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:

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

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

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

(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

Answer Source

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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download