【发布时间】:2019-03-04 03:56:45
【问题描述】:
我正在使用 ng-repeat 重复 ajax 响应提供的问题,我需要每个问题输入的 ng-model 指向一个单独的答案数组。
问题数组如下所示
bookingQuestions: [
0: {
label: 'Any allergies?',
type: 'text',
id: 1234
},
1: {
label: 'Names of attendees',
type: 'text',
id: 1235
}
]
我通过遍历所有问题并将 id 和一个空的 answerValue 属性推送到我的空 bookingAnswers 数组来创建答案数组。 answers 数组如下所示:
bookingAnswers: [
0: {
id: 1234,
answerValue: ''
},
1: {
id: 1235,
answerValue: ''
}
]
在标记中,我试图通过获取正确答案对象以匹配相应问题来初始化answerObj。
<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>
JS函数:
$scope.getAnswerObj = function(question) {
angular.forEach(bookingAnswers, function(answer) {
if(question.id === answer.id) {
return answer.answerValue;
}
});
}
即使 JS 函数成功地返回了正确的对象属性,ng-model 也没有被更新来使用它。我如何让它发挥作用?
【问题讨论】:
标签: javascript angularjs