Reputation: 6868
I have 1 div in which I want to conditionally set background color property of this class. I am using boostrap progress bar and I want to use below class only because it contains some custom settings for progress bar.
Below is my div:
.statistics .progress-bar {
background-color: black;
border-radius: 10px;
line-height: 20px;
text-align: center;
transition: width 0.6s ease 0s;
width: 0;
}
<div class="statistics" ng-repeat="item in data">
<div class="progress-bar" role="progressbar" aria-valuenow="70"
aria-valuemin="0" aria-valuemax="100" ng-style="{'width' : ( item.statistics + '%' )}">
</div>
</div>
Condition is like below :
If statistics > 100
backgroundcolor=red;
else
backgroundcolor=black;
Upvotes: 2
Views: 1160
Reputation: 31841
You can do it using simple expression
ng-style="<condition> ? { <true-value> } : { <false-value> }"
Output
Code:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
</head>
<body ng-controller="myCtrl">
<div ng-style="item.statistics > 100 ? { 'background-color':'red', 'width': item.statistics + '%' }: { 'background-color':'yellow', 'width': item.statistics + '%'}">
<h2>$scope.statistics = {{statistics}}</h2>
</div>
<div ng-style="item.statistics2 > 100 ? { 'background-color':'red', 'width': item.statistics2 + '%' } : { 'background-color':'yellow', 'width': item.statistics2 + '%'}">
<h2>$scope.statistics2 = {{statistics2}}</h2>
</div>
<script>
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", ['$scope', function($scope) {
$scope.item = {};
$scope.item.statistics = 30;
$scope.item.statistics2 = 101;
}]);
</script>
</body>
</html>
Upvotes: 3
Reputation: 18093
You can use ng-class to set dynamically css classes
.statistics .progress-bar {
background-color: black;
border-radius: 10px;
line-height: 20px;
text-align: center;
transition: width 0.6s ease 0s;
width: 0;
color: black
}
.red {
color: red
}
<div class="progress-bar" role="progressbar"
aria-valuenow="70"
aria-valuemin="0" aria-valuemax="100"
ng-style="{'width' : ( item.statistics + '%' )}"
ng-class="{ red: item.statistics > 100 }"
>
If you don't want to create extra classes, you can use ng style :
<div class="progress-bar" role="progressbar"
aria-valuenow="70"
aria-valuemin="0" aria-valuemax="100"
ng-style="getItemStyle(item)">
Then in your controller, you have to create the getItemStyle function :
$scope.getItemStyle = function(item) {
// determine the color
var itemColor = item.statistics > 100 ? 'red' : 'black';
// return object containing the css props
return {
'width': item.statistics + '%',
'color': itemColor
};
};
Upvotes: 1