2016-05-18 48 views
0

说我有对象的数组:基于角度模板中keyvalue的内嵌字体颜色?

var objects = [{'item':'A','type':'Sport'},{'item':'B','type':'Rock'}] 

我想让它这样,如果类型是体育,设置:对于格“红色”。如果type是“Rock”,则为该div设置“color:gray”。

我该如何做这样的事情?

<div ng-repeat="item in objects"> 
    <div style="color:red if item.type='Sport', color:gray if item.type='Rock'">{{item.item}}</div> 
</div> 

回答

0

这是我喜欢的东西在这些情况下做的,使CSS类和串联的类名来使用它......是这样的:

CSS

.type-sport { 
    color: red; 
} 

.type-rock { 
    color: gray; 
} 

HTML

<div ng-repeat="item in objects"> 
    <div class="type-{{:: item.type.toLowerCase() }}">{{item.item}}</div> 
</div> 
+0

巧妙,你是。 – Rolando

+0

谢谢!我还为示例添加了单向绑定(::)以节省手表并避免影响性能,但如果您需要双向绑定,请将其删除 – j3ff

+0

从句法上来说,“::”是什么? – Rolando

0

如果你只有两个条件,那么你可以通过以下代码实现它

<div ng-style="item.type === 'Sport' && {'color':'red'} || item.type === 'Rock' && {'color':'gray'}"</div> 

,如果你有两个以上的条件进行比较,然后使用下面的代码

<div ng-if="'Sport'==item.type" 
       ng-style="{color:'red'}"></div> 
<div ng-if="'Rock'!=item.type" 
       ng-style="{color:'red'}"></div> 

..other条件

0

您可以尝试以下解决方案:

<style> 
    .red-div{ 
    color: red; 
    } 

    .gray-div { 
    color: gray; 
    } 
</style> 

<div ng-repeat="item in objects"> 
    <div ng-class="{'red-div': item.type=='Sport', 'gray-div': item.type=='Rock'}">{{item.item}}</div> 
</div>