Phoenix Phoenix - 2 months ago 8
AngularJS Question

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...

Answer

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