在 ng-options 上使用过滤器来更改显示的值 [英] Use filter on ng-options to change the value displayed
问题描述
我有一组价格(0
、0.99
、1.99
...等),我想在 中显示<选择>
.
I have an array of prices (0
, 0.99
, 1.99
... etc) that I want to display in <select>
.
我想像这样使用Angular的ng-options
I want to use Angular's ng-options
like this
<select ng-model="create_price" ng-options="obj for obj in prices"/>
正如上面显示的那样,它将生成0
、0.99
、1.99
...
As it is displayed above it will generate a selection of 0
, 0.99
, 1.99
...
但我想在代码中使用过滤器,这样每次出现 'prices' 这个词(或类似的东西)时,代码都会运行一个函数来将浮点数更改为字符串和呈现(free
、0.99$
、1.99$
...等).
But I want to use a filter in the code such that every time the word 'prices' is presented (or something like that), the code will run a function to change the float numbers to strings and present (free
, 0.99$
, 1.99$
... etc).
我有办法做到这一点吗?
I there a way to do that?
谢谢
推荐答案
还有更好的方法:
app.filter('price', function() {
return function(num) {
return num === 0 ? 'free' : num + '$';
};
});
然后像这样使用它:
<select ng-model="create_price" ng-options="obj as (obj | price) for obj in prices">
</select>
这样,过滤器对单个值很有用,而不是只对数组进行操作.如果您有对象和相应的格式过滤器,这将非常有用.
This way, the filter is useful for single values, rather than operating only on arrays. If you have objects and corresponding formatting filters, this is quite useful.
过滤器也可以直接在代码中使用,如果你需要它们:
Filters can also be used directly in code, if you need them:
var formattedPrice = $filter('price')(num);
这篇关于在 ng-options 上使用过滤器来更改显示的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!