4

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

2 Answers 2

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 */
}
Sign up to request clarification or add additional context in comments.

2 Comments

I think you can use ng-class and get rid of the {{}}.
@Yann Yeah no point in using class attr when angular provides ng-class. I have updated my answer. Thanks.
5

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)};
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.