Search code examples
javascriptangularjsng-class

How to use ng-class to achieve positive and negative styling angularJs?


I am developing an application that i need to use indicate red for negative and blue for positive of a calculation.

<td class="amount debit">
    <input type="text" class="form-control" ng-model="vm.model.form.amount_debit">
</td>
<td class="amount credit">
    <input type="text" class="form-control" ng-model="vm.model.form.amount_credit">
</td>
<td class="amount balance" ng-class="{
    negative : (book.total_balance + +vm.model.form.amount_debit - +vm.model.form.amount_credit) < 0.00, 
    positive : (book.total_balance + vm.model.form.amount_debit - +vm.model.form.amount_credit) >= 0.00
}">
    @{{vm.model.book.total_balance + +vm.model.form.amount_debit - +vm.model.form.amount_credit| currency:""}}
</td>

In amount balance the amount will be calculated once user input in either input field. The problem is when :

if i input on amount debit input type, it shows me positive value. if i input on amount credit input type, it shows me negative value.

Hence it does not accurately represent the output i wanted.

Let say : balance = 1,000 amount_debit = 300

it will show me total = 1,300 in positive which is correct

then when it is

balance = 1,000 amount_credit = 300

it will show me total = 700 in the NEGATIVE which is incorrect. It should have been still positive.

Is my logic part encountered any error? Or where can i fix? Thank you


Solution

  • I created an example here http://jsfiddle.net/ADukg/12791/

    <table>
    
    <td class="amount balance">
        <input type="number" class="form-control" placeholder="balance" ng-model="total_balance" />
    </td>
    <td class="amount debit">
        <input type="number" class="form-control" placeholder="debit"  ng-model="amount_debit" />
    </td>
    <td class="amount credit">
        <input type="number" class="form-control" placeholder="credit"  ng-model="amount_credit">
    </td>
    <td class="amount balance" ng-class="{
        negative : (total_balance - amount_debit + amount_credit) < 0.00, 
        positive : (total_balance - amount_debit + amount_credit) >= 0.00
    }">
        @{{total_balance - amount_debit + amount_credit | currency:""}}
    </td>
    
    </table>
    

    I used `input type="number" so I don't have to worry about parsing the string into float/int.