Angularjs ng class with various conditions

I have a view that shows data, and I want to add another class to 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 variables called item.date and I want to compare it with other 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 right in my view or do i need to define it in my controller?

early

+4
source share
2 answers

Since you have a bit heavy comparisons, 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 */ } 
+11
source

I think you can use ng-class as follows:

HTML

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

OR moving it inside such a function:

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)}; } 
+5
source

Source: https://habr.com/ru/post/1496780/


All Articles