5

To apply different classes when different expressions evaluate to true:

<div ng-class="{'class1' : expression1, 'class2' : expression2}">
    Hello World!
</div>

To apply different classes a data-bound class using []

 <div ng-class="[class3, class4]">
        Hello World!
    </div>

I want to know if it is possible to combine the two types of template, i.e; have a conditional class using {} and a data-bound class using []?

Any help would be greatly appreciated.

Thanks in advance.

4
  • do you want to add multiple classes when expression gets to true ? Commented Mar 24, 2015 at 11:00
  • yes and also I want to add data bounded classes. Commented Mar 24, 2015 at 11:01
  • didnt clear to me. :( can you give a example ? Commented Mar 24, 2015 at 11:01
  • class3 and class4 are scope variables and I want to apply class1 and class2 based on expression1 and expression2 Commented Mar 24, 2015 at 11:09

2 Answers 2

10
+150

You can use following syntax

<div ng-class="[condition1 && 'class1', condition2 && 'class2', className]">
    Hello World!
</div>

className is a variable in scope. It's value gets applied to div.

Here is a example fiddle Conditionally apply class in angularjs

Sign up to request clarification or add additional context in comments.

1 Comment

This was very helpful, enjoy the bounty.
2

Please see demo below

var app = angular.module('app', []);

app.controller('homeCtrl', function($scope) {


  $scope.redClass = 'red';
  $scope.boldClass = 'bold';

});
.border {
  border: 1px solid red
}
.red {
  color: red
}
.bold {
  font-weight: bold
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app">
  <div ng-controller="homeCtrl">

    <p ng-class="[boldClass ,redClass,  1==1 ? 'border':'' ]">Hello Word</p>

  </div>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.