我有一系列的价格(0
,0.99
,1.99
...等),我想要在<select>
中显示。
我想这样使用Angular的ng-options
<select ng-model="create_price" ng-options="obj for obj in prices"/>
如上面所示,它将生成0
、0.99
、1.99
...
但是我想在代码中使用一个过滤器,这样每次出现单词'prices‘(或类似的东西)时,代码就会运行一个函数,将浮点数更改为字符串并显示(free
,0.99$
,1.99$
...等)。
我有办法做到这一点吗?
谢谢
发布于 2013-05-22 00:55:09
有一个更好的方法:
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>
这样,筛选器对单个值很有用,而不是只对数组进行操作。如果你有对象和相应的格式化过滤器,这是非常有用的。
如果需要,还可以直接在代码中使用过滤器:
var formattedPrice = $filter('price')(num);
发布于 2013-05-20 16:15:14
您希望创建自定义筛选器,例如:
app.filter('price', function() {
return function(arr) {
return arr.map(function(num){
return num === 0 ? 'free' : num + '$';
});
};
});
像这样使用它:
<select ng-model="create_price" ng-options="obj for obj in prices | price">
{{ obj }}
</select>
发布于 2014-05-15 01:14:33
请原谅伪代码
data-ng-options="( obj.property | myFilter ) for obj in objects"
app.filter('myFilter', function() {
return function(displayValue) {
return (should update displayValue) ? 'newDisplayValue' : displayValue;
});
https://stackoverflow.com/questions/16644402
复制相似问题