1

I have a simple dropdown:

 {{x}}            
 <select ng-model="x" ng-options="k for k in [1,2,3]"></select>

easy: {{x}} will be replaced with the selected value 1, 2 or 3.

But what if my data looks like this?

 <select ng-model="x" ng-options="k.a for k in [{a:1},{a:2},{a:3}]">

I want the ones, twos and threes depending on selection but I usually get "{a:1}".

Hm.. this suggests that maybe I won't get what I want. Ideas?

1 Answer 1

3

You're missing just one piece.

If you look at the docs for ng-options, there are several forms the comprehension expression can take.

The form you have is label for value in array. With this form, when you choose an options, it gives you the entire value of the array item, which in your case is something like {a: 1}.

One of the other forms you can use is select as label for value in array. You stick an extra expression in from, and the result of that expression will be bound to your model.

So something like:

ng-options="k.a as k.a for k in [...]"

Then you'll get the value of the a attribute of the selected array item.

Here's a fiddle for you.

Sign up to request clarification or add additional context in comments.

1 Comment

very nice. I had assumed the "as xxx" to be just like the "just a different name" - thing in SQL and therefore had glanced over it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.