我有一个对象数组,用于使用 ng-repeat 呈现单选按钮列表。我的问题是如何绑定(bind)每个问题的选定值并将它们绑定(bind)到某种类型的模型。 这是我到目前为止的 plunker,http://plnkr.co/edit/oXr6Un?p=preview但代码只是循环遍历单选按钮列表并获取选定的值。我真的希望在用户选择答案时绑定(bind)该对象并更改其属性。我怎样才能做到这一点?请理解我是 Angularjs 的新手。 谢谢大家, 回复
最佳答案
就像@Max 上面所说的,您需要在您的输入上设置 ng-model ......然而,这并不是您需要做的全部。 I've forked your plunk and updated it to show you something that works
一些注意事项:
- 您不需要“showAnswers”服务,并且在使用 Angular 时,您永远不必通过 JQuery 从输入中获取值。
- 您需要在输入中添加 ng-model,但您需要在 ng-model 中使用
$parent.answer
,因为输入在ng-repeat 中
有自己的子作用域。 - 您不需要
for=""
标签来包装他们正在标记的输入。
重要变化:
<li ng-repeat="answer in question.answers">
<label>
<input type="radio" ng-model="$parent.question.selectedAnswer"
value="{{ answer.answerText }}" name="quest_{{$parent.$index}}_answers" />{{ answer.answerText }}</label>
</li>
和
$scope.selectedAnswers = function(){
var answers = [];
angular.forEach($scope.questions, function(question) {
answers.push(question.selectedAnswer);
});
return answers;
};
希望对您有所帮助。
关于javascript - 如何获取要绑定(bind)到对象(模型)的多个单选按钮的选定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13634007/