如何获得要绑定到对象(模型)的多个单选按钮的选定值? [英] How can I get the selected values of several radio buttons to be bound to an object (model)?
问题描述
我有一个对象数组,正在使用ng-repeat渲染单选按钮列表.我的问题是如何绑定每个问题的选定值并将其绑定到某种类型的模型.这是我到目前为止拥有的小矮人, http://plnkr.co/edit/oXr6Un?p=预览,但是代码只是循环浏览单选按钮列表并获取选定的值.我真正希望绑定该对象并在用户选择答案时更改其属性.我怎样才能做到这一点?请理解我对Angularjs还是很陌生.谢谢大家,ck
I have an array of objects I am using to render radio button lists using ng-repeat. My question is how can I bind the selected value of each question and bind those to some type of model. Here is the plunker I have so far, http://plnkr.co/edit/oXr6Un?p=preview but the code just loops through the radio button lists and get the selected values. I truly want that object to be bound and change its properties when the user selects an answer. how can I do this? Please understand I am very new to Angularjs. Thanks All, ck
推荐答案
就像上面的@Max一样,您需要在输入中设置ng-model ...但这不是您要做的全部.我已经分叉了你的小酒杯并对其进行了更新,以向您展示一些有用的东西
Like @Max said above, you need to set the ng-model on your inputs... However that's not all you need to do. 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 ="
.
- You didn't need a service to "showAnswers", and you should never have to get values from inputs via JQuery while you're using Angular.
- You needed to add the ng-model in the input, but you need to use
$parent.answer
in the ng-model, because the input was inside of anng-repeat
which has it's own child scope. - You don't need
for=""
on labels that wrap the input they're labeling.
重要更改:
<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;
};
我希望这会有所帮助.
这篇关于如何获得要绑定到对象(模型)的多个单选按钮的选定值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!