Conditionally apply filters with ng-repeat

前端 未结 3 541
忘了有多久
忘了有多久 2021-01-04 18:44

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 (obvio

相关标签:
3条回答
  • 2021-01-04 19:05

    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

    0 讨论(0)
  • 2021-01-04 19:13

    You could try it this way - In your controller, you can have a function which identifies if the provided value is a string or a number:

    $scope.isNumber = function (value) {
        return angular.isNumber(value);
    };
    

    Next, in your view you could have the following:

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

    Thus, when the metricData is a number, it is filtered and when it is a string, it is output as it is.

    0 讨论(0)
  • 2021-01-04 19:17

    I know this is old, but I think the best solution is to move the logic to a filter.

    app.filter("metricDataFilter", function($filter) {
        return function(value) {
          if(angular.isNumber(value)) {
              return $filter("number", value);  
          }
    
          return value;
        }  
    }
    

    That way the HTML is more concise, and angular won't have to redraw dom elements

    <table>
        <tr ng-repeat="(metric, metricData) in data">
            <td>{{metric}}</td>
            <td>{{metricData | metricDataFilter}}</td>
        </tr>
    </table>
    
    0 讨论(0)
提交回复
热议问题