The selected value of my angularjs select is not being set on page refresh.
- It is set if I navigate to a different view and then navigate back again.
- The model for the select is saved to local storage and is initialized into the scope onload.
- I have checked that the data in the scope is the same in the two situations of navigating away and back again, and refreshing the page. The data is exactly the same.
After a lot of investigation, I see that when the select is pristine, or when the page is refreshed, the select list will have an extra blank option, like first one below with value ?
:
<select ng-model="question.answer" class="form-control" ng-options="opt as opt.value for opt in question.options" >
<option value="?" selected="selected"></option>
<option value="0">1</option>
<option value="1">2</option>
</select>
Note The above HTML is the output. My Angular view just has:
<select ng-model="question.answer" class="form-control" ng-options="opt as opt.value for opt in question.options" />
I'm not sure why this would be preventing the correct option from being selected as the correct object is still present at question.answer. See a simplified version of the model below:
var question = {
options: [
{
id: 1,
value: "1"
},
{
id: 2,
value: "2"
}
],
answer: {
id: 2,
value: "2"
}
};
My understanding is that in ng-options
, the first opt
specifies that this is the value that should be assigned to the variable specified in ng-model
. In other words, I will be assigning an object in the options array to question.answer
, rather than just the value. I can see by looking at the model that this is the case.
But I'm not sure how Angular will use the value in question.model
to determine which option is set as selected.
I wonder if the problem is something to do with the fact that the values of the options are set as indices of question.options and it can't work out from question.answer
which index that answer is.
So, I guess my questions are:
- Why is the correct option not being set when this extra <option value="?" selected="selected"></option>
is present?
- How does Angular determine how to use the model to set the selected option (aka - what are those funny indices in the option values?)
Sorry this post is so long. Thank for reading.
Update:
Using the Chrome AngularJS Batarang extension, that the value being set to question.answer
for a picklist is e.g.:
{
$ref: $["options"][1]
}
which will means the value of the picklist is "2".
So that is how it is using the indices of the options are being used, but is that how I have to set my model? i.e. using the $ref
etc?