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 ?
    – Kalhan
    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 ?
    – Kalhan
    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

1
  • This was very helpful, enjoy the bounty.
    – Etheryte
    Commented Jan 24, 2016 at 20:39
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>

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.