Can we have multiple expression to add multiple ng-class ?
for eg.
With multiple conditions
<div ng-class="{'class1' : con1 || can2, 'class2' : con3 && con4}">
Hello World!
</div>
Here is an example comparing multiple angular-ui-router states using the OR || operator:
<li ng-class="
{
warning:
$state.includes('out.pay.code.wrong')
|| $state.includes('out.pay.failed')
,
active:
$state.includes('out.pay')
}
">
It will give the li the classes warning and/or active, depening on whether the conditions are met.
Yes you can have multiple expression to add multiple class in ng-class.
For example:
<div ng-class="{class1:Result.length==2,class2:Result.length==3}"> Dummy Data </div>
Your example works for conditioned classes (the class name will show if the expressionDataX
is true):
<div ng-class="{class1: expressionData1, class2: expressionData2}"></div>
You can also add multiple classes, supplied by the user of the element:
<div ng-class="[class1, class2]"></div>
Usage:
<div class="foo bar" class1="foo" class2="bar"></div>
Using a $scope
method on the controller, you can calculate what classes to output in the view. This is especially handy if you have a complex logic for calculating class names and it will reduce the amount of logic in your view by moving it to the controller:
app.controller('myController', function($scope) {
$scope.className = function() {
var className = 'initClass';
if (condition1())
className += ' class1';
if (condition2())
className += ' class2';
return className;
};
});
and in the view, simply:
<div ng-class="className()"></div>
Other way we can create a function to control "using multiple class"
CSS
<style>
.Red {
color: Red;
}
.Yellow {
color: Yellow;
}
.Blue {
color: Blue;
}
.Green {
color: Green;
}
.Gray {
color: Gray;
}
.b {
font-weight: bold;
}
</style>
Script
<script>
angular.module('myapp', [])
.controller('ExampleController', ['$scope', function ($scope) {
$scope.MyColors = ['It is Red', 'It is Yellow', 'It is Blue', 'It is Green', 'It is Gray'];
$scope.getClass = function (strValue) {
if (strValue == ("It is Red"))
return "Red";
else if (strValue == ("It is Yellow"))
return "Yellow";
else if (strValue == ("It is Blue"))
return "Blue";
else if (strValue == ("It is Green"))
return "Green";
else if (strValue == ("It is Gray"))
return "Gray";
}
}]);
</script>
Using it
<body ng-app="myapp" ng-controller="ExampleController">
<h2>AngularJS ng-class if example</h2>
<ul >
<li ng-repeat="icolor in MyColors" >
<p ng-class="[getClass(icolor), 'b']">{{icolor}}</p>
</li>
</ul>
You can refer to full code page at ng-class if example