How to use both ng-value and ng-class without duplication?

91 views Asked by At

I have an input which uses ng-value with a filter to display a number.

<input ng-value="myDataCollection | customFilter">

I want to also apply ng-class to change the text colour to red if negative.

<input ng-value="myDataCollection | customFilter" ng-class="{'negative-input': (myDataCollection | customFilter) < 0}">

This works, but in my use case the filter has a lot of work to do to calculate the resulting value. The input is also withing a large nested ng-repeat so performance is a concern.

Is it possible to use ng-class based on the resulting value of the input as set by ng-value without having to run through the filter twice?

2

There are 2 answers

0
korteee On

If I am not mistaken as regards the logic you could make use of ng-model instead of ng-value.

Here's a little plunker for you.

0
Dhaval Chaudhary On

This is what I would suggest. You can directly filter the values and save it in some model variable. so it's like you will run you filter on you data collection once and then use it anywhere you want.

$scope.filteredData = yourFilterFunction(yourDataCollection);//this will be filtered data values

 <input ng-value="filteredData" ng-class="{ filteredData < 0 ? 'negative-input': ''}">