2016-05-18 19 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>