根据模型数据有条件地改变img src [英] Conditionally change img src based on model data
问题描述
我想使用 Angular 将模型数据表示为不同的图像,但在找到正确"的方法时遇到了一些麻烦.Angular 关于表达式的 API 文档 说不允许使用条件表达式...
简化很多,模型数据通过 AJAX 获取,并显示路由器上每个接口的状态.类似的东西:
$scope.interfaces = ["UP", "DOWN", "UP", "UP", "UP", "UP", "DOWN"]
所以,在 Angular 中,我们可以用类似的方式显示每个界面的状态:
<li ng-repeat=interface in interfaces>{{interface}}
但是 - 我想展示一个合适的图像,而不是模型中的值.遵循这个总体思路的东西.
<li ng-repeat=interface in interfaces>{{if interface=="UP"}}<img src='green-checkmark.png'>{{别的}}<img src='big-black-X.png'>{{/如果}}
(我认为 Ember 支持这种类型的构造)
当然,我可以修改控制器以根据实际模型数据返回图像 URL,但这似乎违反了模型和视图的分离,不是吗?
此 SO 发布建议使用指令更改 bg-img 源.但后来我们又回到将 URL 放在 JS 中而不是模板中......
感谢所有建议.谢谢.
如有错别字请见谅
你需要 ng-src
而不是 src
.
AngularJS 视图支持二元运算符
条件 &&真||错误的
所以你的 img
标签看起来像这样
<img ng-src="{{interface == 'UP' && 'green-checkmark.png' || 'big-black-X.png'}}"/>
注意:引号(即green-checkmark.png")在这里很重要.如果没有引号,它将无法工作.
plunker here (打开开发工具查看生成的 HTML)>
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
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)
这篇关于根据模型数据有条件地改变img src的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!