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.
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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With