Search code examples
javascripthtmlcssangularjsng-class

Manipulate text with different colors based on multiple conditions


This code uses angularjs ng-table module to display values in a table.

The relevant html code looks like this;

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

The CSS code;

.red { color: red; }

The controller code;

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

The text color will turn red when item.lastPrice < item.price_alert. What if I want the text color to turn red when item.lastPrice < item.price_alert and turn green when item.lastPrice > item.price_alert? Can the code be changed to handle multiple conditions? Something like using a switch statement?


Solution

  • Create a new css class:

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

    And change your ng-class tag according to:

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