最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - angularjs ng-class with different conditions - Stack Overflow

programmeradmin1浏览0评论

i have a view which shows data and i want to add another class on the list items in my view.

<input type="text" class="filter" placeholder="search..." ng-model="search">
<ul>
    <li ng-repeat="item in items | filter:search | orderBy:'date'">
        {{ date }} {{ item.heading }}<button ng-click="deleteItem(item.ID)"><i class='icon-trash'></i></button>
    </li>
</ul>

i have a variables called item.date and i want to compare it to another variables today. Here is the logic:

if (item.date - today <= 0) 
    apply class1 
if else (item.date - today > 0 && item.date - today <= 3)
    apply class2
and so on

how can i achieve this with angular? can i put this logic directly into my view or do i need to define it in my controller?

thanks in advance

i have a view which shows data and i want to add another class on the list items in my view.

<input type="text" class="filter" placeholder="search..." ng-model="search">
<ul>
    <li ng-repeat="item in items | filter:search | orderBy:'date'">
        {{ date }} {{ item.heading }}<button ng-click="deleteItem(item.ID)"><i class='icon-trash'></i></button>
    </li>
</ul>

i have a variables called item.date and i want to compare it to another variables today. Here is the logic:

if (item.date - today <= 0) 
    apply class1 
if else (item.date - today > 0 && item.date - today <= 3)
    apply class2
and so on

how can i achieve this with angular? can i put this logic directly into my view or do i need to define it in my controller?

thanks in advance

Share Improve this question edited Aug 13, 2013 at 11:50 arkhon asked Aug 13, 2013 at 11:43 arkhonarkhon 7652 gold badges12 silver badges28 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 12

Since you have a bit heavy comparisons to make, I would suggest moving it inside a function rather than having it in HTML:

<li ng-class="getClass(item.date)" 
    ng-repeat="item in items | filter:search | orderBy:'date'">

JS:

$scope.getClass = function(date){
    /* comparison logic here*/
    /* returs class name as string */
}

I think you can use ng-class like this:

HTML

<li ng-class="{'class1': item.date - today <= 0, 'class2': (item.date - today > 0 && item.date - today <= 3)}"></li>

OR moving it inside a function like this:

HTML

<li ng-class="getClass(item.date)"></li>

JS

$scope.getClass = function(date){
    return {'class1': item.date - today <= 0, 'class2': (item.date - today > 0 && item.date - today <= 3)};
}
发布评论

评论列表(0)

  1. 暂无评论