Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
963 views
in Technique[技术] by (71.8m points)

angularjs - 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:

<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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...