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

时间:2015-11-22 01:23:51

标签: javascript html css angularjs ng-class

此代码使用angularjs ng-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语句吗?

1 个答案:

答案 0 :(得分:1)

创建一个新的css类:

.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 }> /*....*/