How to apply class conditionally using ng-class in AngularJs

The ngClass directive gives you the ability to conditionally change CSS classes via an expression in the html.

Example that demonstrates dynamically set CSS classes on an DIV HTML element.

Lets say we have a div and need to change the color according to button clicked. We have three buttons for colors: green, red and blue.

  <div style="width:100px;height:100px;margin: 10px;" 
  <button ng-click="setGreen()">Green</button>
  <button ng-click="setRed()">Red</button>
  <button ng-click="setBlue()">Blue</button>

The ngClass directive will work with any expression that evaluates true or false value. In above code css class will be apply according to value of color scope varialbe.

if color value is green then apply greenCss class
if color value is red then apply redCss class
if color value is blue then apply blueCss class

/* Put your css in here */
.greenCss {
  background-color: green;
.redCss {
  background-color: red;
.blueCss {
  background-color: blue;

Assigning value to ‘color’ on the button click events:

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
  $scope.color = 'green';
  $scope.setGreen = function() {
    $scope.color = 'green';
  $scope.setRed = function() {
    $scope.color = 'red';
  $scope.setBlue = function() {
    $scope.color = 'blue';

ngClass in AngularJs