Use filter on ng-options to change the value displayed
Asked Answered
G

3

49

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

Grisham answered 20/5, 2013 at 7:13 Comment(0)
C
113

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);
Cantina answered 21/5, 2013 at 16:55 Comment(3)
Thanks! Except for the syntax error you added - no need for the fourth line round bracket. Beside that the answer works great!Grisham
For clarity, you could add parentheses to the expression: obj as (obj | price) for obj in prices. The syntax is slightly less intimidating.Bloodstone
If any else arrived here in search of a standard currency filter for use with ng-options then this may be useful: option as (option | currency:'$':0) for option in pricesArrFeatherveined
M
7

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>
Melanoid answered 20/5, 2013 at 8:15 Comment(0)
R
2

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;
});
Rodgers answered 14/5, 2014 at 17:14 Comment(2)
Please try to flesh out your answer a bit more. Just posting a code block without any explanation or context is not good. In its current state your answer might not be of much use to people looking for an answer to this question in the future.Significant
Thanks ! This was what I was looking for.. ( obj.property | myFilter ) for obj in objects, but yea, explanation is keyWrangle

© 2022 - 2024 — McMap. All rights reserved.