Phoenix
Phoenix

Reputation: 295

How to check multiple conditions within a td in Angular table?

I need to change the text color of some elements inside TD based on conditions.

My Angular table is :

<table ng-table="employeesList" show-filter="true" class="table table-striped table-bordered">
                    <tr ng-repeat="employee in $data">
                        <td data-title="'#'">{{$index + 1}}</td>
<td data-title="'First Name'" sortable="'firstName'" filter="{ 'firstName': 'text' }">
                            {{employee.employee.firstName}}
                        </td>
 <td data-title="'Current State'" sortable="'currentState'" ng-class="{ red: employee.state.state == 'Available'}">
                            {{employee.state.state}}
                        </td>
</tr>
                </table> 

In the above table, the color of text inside TD with title 'Current state' will change to Red if the condition (employee.state.state == 'Available') is true.

My CSS file :

.red {
color: red;
}
.blue {
color:blue;
}

Similarly I want to have a different color for the same TD if another condition is true. ie, if (employee.state.state == 'Blocked'), I want the text to be in blue color. I have more than 3 states and want a different color for each of the state, so a simple If else won't work.

How can I achieve this?

Thanks in advance...

Upvotes: 0

Views: 1228

Answers (3)

Lekhnath
Lekhnath

Reputation: 4625

If you prefer one line solution, then:

ng-class="{'Available': 'red', 'Blocked': 'blue'}[employee.state.state]"

should do the trick

Upvotes: 1

nikjohn
nikjohn

Reputation: 21802

What you want is something like this:

<td ng-class="employee.state.state == 'Available' ? 'red' : 'blue'">{{employee.state.state}}</td>

If you want more options, you can always extend the operator like so:

<td ng-class="(employee.state.state == 'Available') ? 'red' : (employee.state.state == 'Blocked') ? 'blue'">{{employee.state.state}}</td>

A third and better option would be to write a function here and move the logic to the controller:

<td ng-class="chooseClass">{{employee.state.state}}</td>


// Controller 
$scope.chooseClass = function(employee) {
  switch(employee.state.state) {
    case 'Available':
     return 'red';
     break;
     :
     :
     default:
     return 'white';
  }
}

Upvotes: 1

Razzka
Razzka

Reputation: 641

Try to move this logic into controller:

<td ng-class="calculateClass(employee)">

and in the controller:

$scope.calculateClass = function(employee) {
    var classNames = [];
    switch (employee.state.state) {
        case 'Available':
            classNames.push('red');
        break;
        case 'Blocked':
            classNames.push('blue');
        break;
        default:
        break;
    }

    return classNames;
}

Upvotes: 2

Related Questions