Reputation: 4928
I have asked a question very recently in this post about why my angular select is not setting my select using saved answers.
This is my select:
<select ng-model="question.answer" ng-options="opt as opt.Value for opt in question.options" />
The answer by pkozlowski.opensource tothis stackoverflow post got me thinking that the value that is being set in the ng-model
of my select can't be matching any of the values that are being passed as options in the ng-options
of my select.
I created this jsfiddle that should highlight the issue. Whenever the answer is changed the answer object is logged to the console. (Note that for some reason it is being logged twice in jsfiddle, but it's only being logged once when I run the same code locally on my machine)
You can see that when the button is pressed, the answer logged out is the same object structure as the third option, but the picklist is set to a blank option.
Output logged to console after setting the picklist to the third option:
answer is: picklistTest.js:25
Object {id: 3, Value: "Three"}
Output logged to console after clicking the "setToThirdAnswer" button:
answer is: picklistTest.js:25
Object {id: 3, Value: "Three"}
It is the same structure, but not the same object. So I wondered if the object in the model has to be exactly the same object as one of the options.
This second jsfiddle shows that that is the case. The button is setting the answer to be a reference to one of the option objects.
So, I'm happy that I have found out why my selects weren't setting the selected value after a page refresh, but now I would really like to know (and this must be a very common use case):
If my options are objects and I am setting the whole object to the ng-model
, how can I use saved json to re-render the form without first doing some processing on the client side?
var json = question = {
options: [
{
id: 1,
Value: "One"
},
{
id: 2,
Value: "Two"
},
{
id: 3,
Value: "Three"
}
],
answer: {
id: 3,
Value: "Three"
}
};
because the answer object and the third value of the options array aren't the same object, but you can't represent a reference in json (can you?).
Upvotes: 1
Views: 532
Reputation: 1266
The ng-options attribute has a track by
expression to do just what you're talking about:
ng-options="opt as opt.Value for opt in question.options track by opt.id"
See the updated fiddle: http://jsfiddle.net/CkLEu/6/
Upvotes: 2
Reputation: 28750
Yes, you need to have the same reference. You can do this like so:
question.answer = question.options[2]
Directly after you create it.
Upvotes: 1