AngularJS ng-class example

AngularJS ng-class directive allows you to dynamically set CSS classes on an element using an expression. The expression can be of one of these three types.

  1. String (one or more space delimited classes). e.g.
    <div ng-class="style1"</div>
    <div ng-class="style1 stye2"</div>

  2. object (key is class name and it value can be true/false). All object keys with true value are applied as classes to element. e.g.
    <div ng-class="{class1: isClass1, class2: isClass2}"</div>

  3. array (it can contains string and objects). e.g.
    <div ng-class="[style1, style2, style3]"</div>


.redBg {background-color: red;}
.blueBorder {border: 2px solid blue;}

<div ng-app="myApp" ng-controller='MyCtrl'>
  Set red background: <input type="checkbox" ng-model="isRedBg">{{isRedBg}}<br>
  Set Blue border: <input type="checkbox" ng-model="isBlueBorder"><br>
  <div ng-class="{redBg: isRedBg, blueBorder: isBlueBorder}">Hello</div>

<script src="//"></script>
  var module = angular.module('myApp', []);
  module.controller('MyCtrl', function($scope) {});
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments