2014-02-20 154 views
1

剛剛在Angular.js中啓動,並且遇到了一個小小的呃逆,它比應該弄清楚的時間要長很多。我有3組4個單選按鈕。我試圖訪問用戶在每組中選擇的單選按鈕。問題到目前爲止,我只能用一套。如果有多個組,則在用戶選擇一個單選按鈕後,所有組將切換到該選定的單選按鈕。我很確定它與我的ng-model =「$ parent.selected」有關,但我不確定如何解決它。從Angular.js中的不同組單選按鈕中選擇單選按鈕

我不能讓與的jsfiddle角工作由於某種原因,所以這裏就是我:

HTML:

<form name="myForm" ng-controller="testController"> 

    <div ng-repeat="question in questions | limitTo:3"> 

    <div>{{question.Question}}</div> 

    <input type="radio" ng-model="$parent.selected" value="A" name="{{question.id}}" />{{question.A}}<br /> 
    <input type="radio" ng-model="$parent.selected" value="B" name="{{question.id}}" />{{question.B}}<br /> 
    <input type="radio" ng-model="$parent.selected" value="C" name="{{question.id}}" />{{question.C}}<br /> 
    <input type="radio" ng-model="$parent.selected" value="D" name="{{question.id}}" />{{question.D}}<br /> 

    Selected = {{selected}} 

    </div> 

</form> 

JS:

angular.module('nodeServerApp') 
.controller('testController', function ($scope) { 

$scope.questions = 
[ 
    { 
     "id": 0, 
     "Question": "Is C the right answer?", 
     "A": "This is choice A.", 
     "B": "This is choice B.", 
     "C": "This is choice C.", 
     "D": "This is choice D.", 
     "Answer": "C" 
    }, 
    { 
     "id": 1, 
     "Question": "Is A the right answer?", 
     "A": "This is choice A.", 
     "B": "This is choice B.", 
     "C": "This is choice C.", 
     "D": "This is choice D.", 
     "Answer": "A" 
    }, 
    { 
     "id": 2, 
     "Question": "Is D the right answer?", 
     "A": "This is choice A.", 
     "B": "This is choice B.", 
     "C": "This is choice C.", 
     "D": "This is choice D.", 
     "Answer": "D" 
    } 
]; 

}); 

回答

2

ngModel應該是selected,不是$parent.selected(這將會被所有問題共享)...

<input type="radio" ng-model="selected" value="A" name="{{question.id}}" />{{question.A}}<br /> 
<input type="radio" ng-model="selected" value="B" name="{{question.id}}" />{{question.B}}<br /> 
<input type="radio" ng-model="selected" value="C" name="{{question.id}}" />{{question.C}}<br /> 
<input type="radio" ng-model="selected" value="D" name="{{question.id}}" />{{question.D}}<br /> 

Selected = {{selected}} 

還考慮把selectedquestion所以一切都是在同一個地方......

<input type="radio" ng-model="question.selected" value="A" name="{{question.id}}" />{{question.A}}<br /> 
<input type="radio" ng-model="question.selected" value="B" name="{{question.id}}" />{{question.B}}<br /> 
<input type="radio" ng-model="question.selected" value="C" name="{{question.id}}" />{{question.C}}<br /> 
<input type="radio" ng-model="question.selected" value="D" name="{{question.id}}" />{{question.D}}<br /> 

Selected = {{question.selected}} {{question.selected === question.Answer ? "Correct" : "Incorrect"}}