Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular JS - Number filter - Change colour when negative

I am applying a number filter to the result of a function:

<tr class="text-center">
    <th class="text-center">{{monthCategoryTotalPredict = getCategoryMonthTotal(costDirection, month, category, "predict")  | currency:currencySymbol}}</th>
    <th class="text-center">{{monthCategoryTotalActual  = getCategoryMonthTotal(costDirection, month, category, "actual")   | currency:currencySymbol}}</th>
    <th class="text-center">{{calculateSurplus(monthCategoryTotalPredict, monthCategoryTotalActual)  | currency:currencySymbol}}</th>
</tr>

Negative numbers are represented like this by default: (£230.00).

My aim is to make them also change colour to red. How can I do this in Angular JS? Can this be part of the filter? Can I override the filter to modify it's default behaviour slightly without a complete rewrite?

Thanks in advance!

like image 681
iamyojimbo Avatar asked Dec 30 '13 17:12

iamyojimbo


1 Answers

In order to change the color of text in HTML, you'll need to modify it's container element. Since the filter doesn't know about the element, you can either inject one (bad idea), or use a directive instead of a filter.

Putting a function in your code is actually a bad way to handle things. It may have to fire multiple times, and will certainly screw up any kind of sorting you attempt.

<th class="text-center" ng-class="{ red: calculateSurplus(monthCategoryTotalPredict, monthCategoryTotalActual) < 0 }">{{calculateSurplus(monthCategoryTotalPredict, monthCategoryTotalActual)  | currency:currencySymbol}}</th>

I would honestly perform these calculations ahead of time, so that it looks like this.

<th class="text-center" ng-class="{ red: surplus < 0 }">{{surplus | currency:currencySymbol}}</th>
like image 95
Mike Robinson Avatar answered Oct 25 '22 09:10

Mike Robinson