The ngChange
directive requires ngModel
to be present, but binding directly to a field in my controller is difficult, because the logic is a little more complicated.
I have a questionnaire containing questions retrieved from a database. Each question may have an answer already and I can retrieve that with a call to a method on the survey being viewed:
vm.survey.GetCurrentAnswerIDForQuestionID(q.ID)
When updating, it is difficult to bind directly to a property because if the answer isn't present I need to create an entity to store it, and if it is present then I change it or delete it (when the user selects the empty option).
So I figure that I need to call a method instead. Like this:
vm.survey.SetCurrentAnswerIDForQuestionID(q.ID, answerid)
I can display the select list correctly using this markup:
<select ng-init="answerid = vm.survey.GetCurrentAnswerIDForQuestionID(q.ID)">
<option value=""></option>
<option ng-repeat="va in q.ValidAnswers | orderBy:'SortOrder'"
ng-selected="va.AnswerID === q.currentAnswer"
value="{{va.AnswerID}}">
{{va.Text}}
</option>
</select>
Now I want to call a method to set the answer when the user changes the answer. Something like this:
<select
ng-init="answerid = vm.survey.GetCurrentAnswerIDForQuestionID(q.ID)"
ng-model="answerid"
ng-change="vm.survey.SetCurrentAnswerIDForQuestionID(q.ID, answerid)">
...etc
But that doesn't work - the correct item is no longer selected when I view the page
You should be using ngOptions
to get the bindings to work correctly:
<select
ng-init="answerid = vm.survey.GetCurrentAnswerIDForQuestionID(q.ID)"
ng-model="answerid"
ng-change="vm.survey.SetCurrentAnswerIDForQuestionID(q.ID, answerid)"
ng-options="va.AnswerID as va.Text for va in q.ValidAnswers"
></select>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With