Use filter on ng-options to change the value displayed

大城市里の小女人 提交于 2019-11-26 12:57:58

问题


I have an array of prices (0, 0.99, 1.99... etc) that I want to display in <select>.

I want to use Angular\'s ng-options like this

<select ng-model=\"create_price\" ng-options=\"obj for obj in prices\"/>

As it is displayed above it will generate a selection of 0, 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?

Thanks


回答1:


There's a better way:

app.filter('price', function() {
  return function(num) {
    return num === 0 ? 'free' : num + '$';
  };
});

Then use it like this:

<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);



回答2:


You want to create the custom filter such as:

app.filter('price', function() {
  return function(arr) {
    return arr.map(function(num){
      return num === 0 ? 'free' : num + '$';
    });
  };
});

use it like:

<select ng-model="create_price" ng-options="obj for obj in prices | price">
  {{ obj }}
</select>



回答3:


Pardon the pseudo code

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/use-filter-on-ng-options-to-change-the-value-displayed

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