javascript 不同条件下的angularjs ng-class

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18208211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:05:06  来源:igfitidea点击:

angularjs ng-class with different conditions

javascriptangularjs

提问by arkhon

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.dateand i want to compare it to another variables today. Here is the logic:

我有一个名为item.date的变量,我想将它与今天的另一个变量进行比较。这是逻辑:

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?

我怎样才能用 angular 实现这一点?我可以将此逻辑直接放入我的视图中还是需要在我的控制器中定义它?

thanks in advance

提前致谢

回答by AlwaysALearner

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

由于您需要进行一些比较繁重的比较,我建议将其移到函数中,而不是将其放在 HTML 中:

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

JS:

JS:

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

回答by EpokK

I think you can use ng-classlike this:

我认为你可以这样使用ng-class

HTML

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

HTML

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

JS

JS

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