Add class dynamically using angularjs

Rakesh Sharma      No Comments  

How to add class dynamically using angularjs with examples

Add class dynamically using angularjs

If you are working with angularjs. Then you will found there are many of directives exist to make your work easy. Like similiar using ngClass directive we can easily remove or add class dynamically using angularjs. Below we’ll look some quick example of some fun stuff you can do by dynamically/conditionally adding classes.

Add class dynamically using angularjs variable

This is an example of add class using angularjs variable directly in class attribute. we are using ng-model="btnClass" to bind value to scope and then adding this scope/angular variable value to class attribute with class="btn btn-{{btnClass}}"


Using ngClass

Now we will use ngClass to apply classes conditionally. In this examples and tutorials here, we’ll be using input text and check boxes to dynamically/conditionally add classes to our HTML elements. Let’s see some example using ngClass.

Apply dynamic class Using String Syntax

This is easiest way to use ngClass. We just need to add an Angular variable to ng-class. This will the class we are applying to element.

<!-- Typed value -->
<input type="text" ng-model="btnClass" class="form-control">
<!-- class will be apply what you typing -->
<div ng-class="btnClass">Using ng-class</div>

Let’s see a full example of add conditionally/dynamically add class using ngClass using string syntax.

Apply dynamic class Using Evaluated Expression

Now we will see an example of adding class dynamically on evaluated expression using ngClass. So our class will be apply on result of expression. which result will be true will be apply certain class.

<!-- toogle a value true of false -->
<input type="checkbox" ng-model="red">
<input type="checkbox" ng-model="green">
<!-- adding a condition on ng-class -->
<div ng-class="{danger: red, success: green}">Using ng-class conditionally</div>

Now we are evaluating an expression to apply class. we are using {} to make condition seperate. Now which value will be return true will be apply certain class on checkbox checked.

Let’s see a example of ngClass on Evaluated Expression.

So now you can see use of ngClass. and you easily done adding classes dynamically/conditionally using angularjs in your application.