Hopefully someone can point me in the right direction. I'm currently extremely stumped on how to achieve the following -
I'm trying to use ng-class within ng-repeat to conditionally apply a bootstrap background-color class.
Simple enough and works great when I input a static value to compare to (in this case "25") -
In the controller. Data is coming from firebase. The data is stuctured like so -
"myDatabase": { "someNumber":"12" }
"myOtherDatabase": { "compNumber":"30" }
var ref = new Firebase(my-first-firebase-url);
$scope.data = $firebase(ref);
var ref2 = new Firebase(my-second-firebase-url);
$scope.data2 =$firebase(ref2);
In the View -
<div ng-repeat="item in data" ng-class="{'bg-info' : item.someNumber > 25}"> {{item.someNumber}} </div>
However I would like to make the comparison value pulled dynamically from a SEPERATE firebase object that I'm updating with a separate $watch function. Obviously the following doesn't work but how can I achieve the intended results...
<div ng-repeat="item in data" ng-class="{'bg-info' : item.someNumber > data2.compNumber}"> {{item.someNumber}} </div>
any help is much appreciated!!
I would create a function in the $scope to generate the classes to be inserted in the HTML. I always prefer to have this kind of logic in the JS part, and in this specific case is specially important because you need to first convert your value from string to number.
Here is a small example:
angular.module('webapp', [])
.controller('dummyCtrl', ['$scope', '$timeout', function($scope, $timeout) {
$scope.data = [{
value: '1'
},
{
value: '40'
},
{
value: '20'
},
{
value: '10'
},
{
value: '50'
},
{
value: '20'
}
];
$scope.threshold = 30;
$scope.getClass = function(item) {
return {
'bg-info': Number(item.value) > $scope.threshold
};
};
}]);
.bg-info {
background-color: red;
}
<!DOCTYPE html>
<html ng-app="webapp">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
</head>
<body ng-app="webapp">
<div ng-controller="dummyCtrl">
<div ng-repeat="item in data" ng-class="getClass(item)"> {{item.value}}</div>
</div>
</body>
</html>