English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

AngularJS ng-class directive

AngularJS Reference Manual

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>
<style>
.sky {
    color:white;
    background-color:lightblue;
    padding:20px;
    font-family:"Courier New";
}
.tomato {
    background-color:coral;
    padding:40px;
    font-family:Verdana;
}
</style>
</head>
<body ng-app="">
<p>Select a class:</p>/p>
<select ng-model="home">
<option value="sky">Sky Color</option>
<option value="tomato">Tomato Color</option>
</select>
<div ng-class="home">
  <h1>Welcome Home!/h1>
  <p>I like it!/p>
</div>
</body>
</html>
Test and See ‹/›

Definition and Usage

ng-class The directive is used to dynamically bind one or more CSS classes to an HTML element.

ng-class The value of the directive can be a string, an object, or an array.

If it is a string, multiple class names are separated by spaces.

If it is an object, a key is required-value pair, with the key as the class name you want to add, and the value is a boolean value. The class will be added only when the value is true.

If it is an array, it can be composed of strings or objects, and the elements of the array can be strings or objects.

Syntax

   <element ng-class="expression"></element>

All HTML elements support it.

Parameter Value

ValueDescription
expressionThe expression returns one or more class names.

AngularJS Reference Manual