Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to combine conditional class and data bound class in angularjs

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.

like image 671
satish kumar V Avatar asked Mar 24 '15 10:03

satish kumar V


2 Answers

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

like image 84
Ranadheer Reddy Avatar answered Nov 15 '22 08:11

Ranadheer Reddy


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>
like image 43
sylwester Avatar answered Nov 15 '22 08:11

sylwester