我正在使用 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 数组中来创建答案数组。答案数组如下所示:
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 也不会更新以使用它。我如何让这个工作?
您将所有输入的 ng-model 绑定到某种answerObj
含义,它们都指向同一个变量。使用$index
您可以访问当前迭代的索引。所以你可以做这样的事情:
<input type=“text“ name="{{question.id}}"
ng-model="bookingAnswers[$index].answerValue"> </div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句