Conditionally apply filters with ng-repeat

不羁的心 提交于 2019-11-30 18:49:00

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

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.

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!