I have a set of questions coming from an AJAX response that I am displaying using ng-repeat. Each question input in the list needs to be connected to a separate answers array through its ng-model.
Here is an example of how the question array looks:
bookingQuestions: [
0: {
label: 'Any allergies?',
type: 'text',
id: 1234
},
1: {
label: 'Names of attendees',
type: 'text',
id: 1235
}
]
To handle this, I loop through all questions and create an answers array by assigning each question with its corresponding empty answerValue property. The structure of the answers array is as follows:
bookingAnswers: [
0: {
id: 1234,
answerValue: ''
},
1: {
id: 1235,
answerValue: ''
}
]
Within my markup, I am trying to initialize the answerObj variable by matching it with the correct answer object based on the respective question.
<div class="question" ng-repeat="question in bookingQuestions">
<label class="question-label" for="{{question.id}}">{{question.label}}
</label>
<input type="text" name="{{question.id}}" ng-model="answerObj"
ng-init="answerObj = getAnswerObj(question)">
</div>
The JavaScript function involved in retrieving the correct answer object is shown below:
$scope.getAnswerObj = function(question) {
angular.forEach(bookingAnswers, function(answer) {
if(question.id === answer.id) {
return answer.answerValue;
}
});
}
Although the JavaScript function is successfully returning the desired object property, the ng-model is not getting updated accordingly. How can I resolve this issue?