【问题标题】:Manipulate text with different colors based on multiple conditions根据多个条件处理不同颜色的文本
【发布时间】:2015-11-22 09:26:14
【问题描述】:

此代码使用 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 &lt; item.price_alert 时文本颜色会变为红色。如果我希望文本颜色在item.lastPrice &lt; item.price_alert 时变为红色,而在item.lastPrice &gt; item.price_alert 时变为绿色怎么办?可以更改代码以处理多个条件吗?类似于使用 switch 语句?

【问题讨论】:

    标签: javascript html css angularjs ng-class


    【解决方案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 }> /*....*/
    

    【讨论】:

    • 我不知道可以通过这种方式使用 ng-class 添加多个条件。谢谢!
    猜你喜欢
    • 2021-01-09
    • 2016-11-18
    • 2022-07-21
    • 2016-12-17
    • 2014-10-22
    • 2018-06-19
    • 2019-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多