【问题标题】:How to check multiple conditions within a td in Angular table?如何检查 Angular 表中 td 内的多个条件?
【发布时间】:2017-01-27 00:46:47
【问题描述】:

我需要根据条件更改TD内部某些元素的文本颜色。

我的 Angular 表是:

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

在上表中,如果条件 (employee.state.state == 'Available') 为真,TD 内标题为“Current state”的文本颜色将变为红色。

我的 CSS 文件:

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

同样,如果另一个条件为真,我想为同一个 TD 使用不同的颜色。 即,如果(employee.state.state == 'Blocked'),我希望文本为蓝色。我有超过 3 个州,并且想要为每个州使用不同的颜色,所以简单的 If else 行不通。

我怎样才能做到这一点?

提前谢谢...

【问题讨论】:

    标签: css angularjs datatable


    【解决方案1】:

    尝试将此逻辑移动到控制器中:

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

    在控制器中:

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

    【讨论】:

      【解决方案2】:

      你想要的是这样的:

      &lt;td ng-class="employee.state.state == 'Available' ? 'red' : 'blue'"&gt;{{employee.state.state}}&lt;/td&gt;

      如果你想要更多的选项,你可以像这样扩展操作符:

      &lt;td ng-class="(employee.state.state == 'Available') ? 'red' : (employee.state.state == 'Blocked') ? 'blue'"&gt;{{employee.state.state}}&lt;/td&gt;

      第三种更好的选择是在这里编写一个函数并将逻辑移动到控制器:

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

      【讨论】:

      • 感谢您查看这个问题!我真正想要的是我所有州的不同颜色......即,有超过 2 个州。我会在我的问题中提到同样的内容以避免再次混淆。
      • 再次感谢您的帮助。当我第一次得到它时,将另一个标记为答案。赞成你的,因为这也有效。 :)
      【解决方案3】:

      如果您更喜欢单线解决方案,那么:

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

      应该做的伎俩

      【讨论】:

        猜你喜欢
        • 2019-10-23
        • 2020-09-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-31
        • 1970-01-01
        • 2019-03-22
        • 1970-01-01
        相关资源
        最近更新 更多