How to conditionally apply CSS classes using AngularJS ng-class

Waqas Anwar
13 February 2016
2092 Views

If you are displaying data from the database and you want to apply different CSS classes based on certain condition, you can using AngularJS built in directive ng-class

AngularJS

(function () {
   'use strict';

   angular
      .module('app', [])
      .controller('DemoController', DemoController);

      function DemoController (){
         var vm = this;
         vm.users = [
            {Id: 1, Name: "Joseph", Status: true},
            {Id: 2, Name: "Peter", Status: false},
            {Id: 3, Name: "Parker", Status: true},
            {Id: 4, Name: "Mark", Status: false},
         ];
      }
})();

HTML

<!DOCTYPE html>
<html lang="en-US">
   <head> 
      <style type="text/css">
         table{ border-collapse: collapse; width: 400px; }
         td { padding: 5px; }
         .approved { background-color: #99ff99; }
         .notApproved { background-color: #FF0000; color: #ffffff; }
      </style>
   </head>
<body ng-app="app">

<div ng-controller="DemoController as vm">
   <table>
      <tr ng-repeat="user in vm.users" ng-class="{'approved': user.Status, 'notApproved': !user.Status}">
         <td>{{user.Id}}</td>
         <td>{{user.Name}}</td>
         <td>{{user.Status}}</td>
      </tr> 
   </table>
</div>

<script src="angular.min.js"></script>
<script src="app.js"></script>

</body>
</html>

Output

1 Joseph true
2 Peter false
3 Parker true
4 Mark false