根据多种条件处理不同颜色的文本

Manipulate text with different colors based on multiple conditions

此代码使用 angularjs ng-table 模块在 table 中显示值。

相关的 html 代码如下所示;

<div ng-controller="ViewCtrl" class="container">
    <table ng-table="tableParams" class="table table-bordered">
        <thead>

        <tr>            
            <th>price_alert</th>
            <th>lastPrice</th>
        </tr>

        <thead>
        <tbody>
        <tr ng-repeat="item in $data">
            <td data-title="'price_alert'" ng-class="{ red: item.lastPrice < stk.price_alert }>
                ${{item.price_alert}}
            </td>
            <td data-title="'lastPrice'" ng-class="{ red: item.lastPrice < stk.price_alert }>
                ${{item.lastPrice}}
            </td>
        </tr>
        </tbody>
        </tbody>
    </table>
</div>

CSS代码;

.red { color: red; }

控制器代码;

controller('ViewCtrl', ['$scope', '$http', 'moment', 'ngTableParams',
        function ($scope, $http, $timeout, $window, $configuration, $moment, ngTableParams) {
            var tableData = [];
            //Table configuration
            $scope.tableParams = new ngTableParams({
                page: 1,
                count: 100
            },{
                total:tableData.length,
                //Returns the data for rendering
                getData : function($defer,params){
                    var url = 'http://127.0.0.1/list';
                    $http.get(url).then(function(response) {
                        tableData = response.data;
                        $defer.resolve(tableData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                        params.total(tableData.length);
                    });
                }
            });
        }])

item.lastPrice < item.price_alert时文字颜色会变成红色。如果我想让文字颜色在 item.lastPrice < item.price_alert 时变成红色,在 item.lastPrice > item.price_alert 时变成绿色怎么办?可以更改代码以处理多种情况吗?类似于使用 switch 语句?

创建一个新的 css class:

.red { color: red; }
.green { color: green; }

并根据以下内容更改您的 ng-class 标签:

<td data-title="'price_alert'" ng-class="{ red: item.lastPrice < stk.price_alert, green: item.lastPrice > item.price_alert }> /*....*/