使用 ng-repeat 有条件地应用过滤器 [英] Conditionally apply filters with ng-repeat
问题描述
我有一个包含数字和文本混合值的对象.当对象是数字时,我想将 numbers
过滤器应用于对象的值(显然).但是当它不是一个数字时,我只需要吐出字符串就可以了.按原样,应用 |number
到值格式化数字,但将字符串值留空(毕竟,它们不是数字).
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).
我猜它必须是一个自定义过滤器(我还需要制作).在执行 ng-repeat
时,有没有办法仅在 HTML 中执行此操作?
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
};
推荐答案
这是@callmekatootie 使用 ng-if
(v1.1.5) 请求的答案的替代版本:
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>
这样做的优点是只对数字元素运行过滤器.在这种情况下,这可能没什么好处,但在其他更复杂的过滤器情况下可能有用.要回答有关内置 angular.isNumber
的其他问题,@callmekatootie 确实在作用域函数 isNumber
中使用了它,它只是使用内置函数的包装器在视图中.
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.
这篇关于使用 ng-repeat 有条件地应用过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!