Search code examples
javascriptangularjsangularjs-ng-repeatangular-filters

AngularJs: How to add a custom filter inside an ngRepeat to manipulate decimals?


I have a single object of multiple property names and values that are being printed out via ng-repeat. Two of the objects inside this large object, are called currencyName and currencyPrice.

By default, these objects have 8 decimals hardcoded into them in the backend, and my task is to manipulate certain currencyName to show 5 decimals, or 8 decimals in the display page with Angular. By default, the currencyPrices have 8 decimals hardcoded into them on the backend, which cannot be touched since that bit of code is reused in other places. For the display page I'm working on, we use the filter | number:2 by default.

I tried to create a custom filter that will target the array of the main object, run a for loop/forEach method, target the currencyName object, and if it matches an array that contains currencyNames to be manipulated, the angular display page will show 5 decimals (in this case).

This has proven very difficult to me. I don't have the full code to paste it here, but here's some sample code to show what the code looks.

<tr ng-repeat="full in fulls.mainList" class="animate-repeat">
  <td>{{full.currencyName}}</td>
  <td>{{full.tradedAverage | number:2}}</td>
  <td>{{full.tradedAmount | number:2}}</td>
  <td>{{full.currencyPrice | number:2}}</td>
</tr>

fulls in this case is the large object that's being parsed inside the controller.


Solution

  • Tested your code and it should work:

       <div ng-repeat="full in fulls.mainList">
           <span>{{full.currencyName}}</span>
           <span>{{full.tradedAverage | number:2}}</span>
           <span>{{full.tradedAmount | number:2}}</span>
           <span>{{full.currencyPrice | number:2}}</span>
       </div>
    
        $scope.fulls = {
              mainList : [
                {
                  currencyName: 'TEST',
                  tradedAverage: '12.123434',
                  tradedAmount: '13.133434',
                  currencyPrice: '14.143434'
                }
              ]
           };
    

    http://jsfiddle.net/Lvc0u55v/1/

    Maybe you have ',' instead of '.' in your numbers?