javascripthtmlangularjsangularjs-ng-repeatangularjs-filter

Conditionally apply filters with ng-repeat


I have an object that contains a mixture of numbers and text for values. I'd like to apply the numbers filter to the object's value when it's a number (obviously). But when it isn't a number, I'd be okay with it just spitting out the string. As is, applying | number to the value formats the numbers, but leaves the string values empty (afterall, they aren't numbers).

I'm guessing it'll have to be a custom filter (which I have yet had a need to make). Is there a way to do it solely within the HTML when doing the ng-repeat?

<table>
      <tr ng-repeat="(metric, metricData) in data">
        <td>{{metric}}</td>
        <td>{{metricData | number}}</td>
      </tr>
</table>

$scope.data = { name:"this is the name", 
                score:48
                outcome:"as expected",
                attendance:820,
                total:212.34
              };

Solution

  • Here is the requested alternate version of the answer from @callmekatootie using ng-if (v1.1.5):

    <table>
        <tr ng-repeat="(metric, metricData) in data">
            <td>{{metric}}</td>
            <td ng-if="isNumber(metricData)">{{metricData | number}}</td>
            <td ng-if="!isNumber(metricData)">{{metricData}}</td>
        </tr>
    </table>
    

    This has the advantage of only running the filter on the elements which are numeric. This is probably of little benefit in this case but may be useful in other more complex filter situations. To answer your other question about the built-in angular.isNumber, @callmekatootie does use that in the scope function isNumber, which is only a wrapper for using the built-in in the view.

    Here is a fiddle