Search code examples
javascriptcssangularjsng-class

How to use ng-class in angularjs table?


I have 3 css class namely

.green{
  background-color:green
}

.yellow{
  background-color:yellow
}

.red{
  background-color:red
}

And I have a table

which looks like this

<div class="table-responsive">
    <table class="table table-bordered">
        <thead>
        <tr class="bg-primary">
            <th>Task Name</th>
            <th>Start Date</th>
            <th>End Date</th>
            <th>Priority</th>
            <th>Action</th>
            <th ng-hide="true">autoid</th>
        </tr>
        </thead>
        <tbody>
        <tr ng-repeat="d in dataintbl">
            <td>{{d.taskname}}</td>
            <td>{{d.taskstartdate}}</td>
            <td>{{d.taskenddate}}</td>
            <td>{{d.taskpriority}}</td>
            <td>
                <a href="#" ng-click="updateuser()" class="btn btn-warning glyphicon glyphicon-edit"></a>
                <a href="#" ng-click="deleteuser()" class="btn btn-danger glyphicon glyphicon-trash"></a>
            </td>
            <td ng-hide="true">{{d.taskmid}}</td>
        </tr>
        </tbody>
    </table>
</div>

now in my <td>{{d.taskpriority}}</td>I have data like

low medium high

now I want to use ng-class in my td and apply css class as per data

if I have (low) in my td, green css class should be apply and so on

what I need to do to achieve this?


Solution

  • This should work.

    <td ng-class="{'green': (d.taskpriority == 'low'), 'yellow': (d.taskpriority == 'medium'), 'red': (d.taskpriority == 'high')}">{{d.taskpriority}}</td> 
    

    ng-class accepts a map of class names to boolean values. See documentation