I am trying to understand how to accomplish conditional formatting with AngularJS.
My scenerio, I have a table with a bunch of values like this:
<tr ng-repeat='r in row'>
<td>{{r.valueA | number:0}}</td>
<td>{{r.valueB | number:0}}</td>
<td>{{r.valueA - r.valueB | number:0}}</td>
<td>{{total.valueA - r.valueA | number:0}}</td>
<td>{{total.valueA - (r.valueA - r.valueB | number:0)}}</td>
</tr>
What I want to happen is for these cells to change the text red when the number is negative.
Below is what I have tried:
A) Using the ng-class directive route:
<tr ng-repeat='r in row'>
<td ng-class="{'text-red':r.valueA < 0}">{{r.valueA | number:0}}</td>
<td ng-class="{'text-red':r.valueB < 0}">{{r.valueB | number:0}}</td>
<td ng-class="{'text-red':(r.valueA - r.valueB) < 0}">{{r.valueA - r.valueB | number:0}}</td>
<td ng-class="{'text-red':(total.valueA - r.valueA) < 0}">{{total.valueA - r.valueA | number:0}}</td>
<td ng-class="{'text-red':(total.valueA - (r.valueA - r.valueB)) < 0}">{{total.valueA - (r.valueA - r.valueB) | number:0}}</td>
</tr>
...and it works, but there is a lot of needless typing. Surely there is a better way.
B) A custom filter but cannot get it to work:
myApp.filter('numberVariance',
['$filter',
function (filter) {
var numberFilter = filter('number');
return function (amount, fractionDigits) {
if (value === "0") {
return "-";
}
var value = numberFilter(amount, fractionDigits);
if (amount < 0)
return "<span class='text-red'>" + value + "</span>";
return value;
};
}]);
...this escapes the returned HTML string. I would rather find a solution that does not use ng-html-bind or "unsafe" strings.
C) A custom directive. This feels like it is the best fit, but I cannot get this to work either:
myApp.directive('varianceValue', function () {
return {
restrict: 'A',
link: function (scope, el, attr) {
$(el).toggleClass("text-red", ($(el).text().indexOf('-') > -1));
},
}
});
...this works fine on first load, but does not toggle the class as the value updates.