简体   繁体   中英

Angular not updating radio button selection

I have a small quiz application that I am converting into angular. It displays a question, and 4 possible answers that you select through radio buttons. You can move to the next question or back to the original and your selection is noted.

I am having problems reselecting the radio button when I want to go back to the question. The attribute for the button states that I have changed it to true, but it is not indicated. Only when I go back to the first question, and try to go back a second time does it update correctly. I am assuming that since it can't back back any further and can run again that there is some updating to the buttons going on and that is what is doing it.

The extra space appears to be a formatting issue with stack overflow, it isn't in my actual code base. I have since remove it.

Any help would be greatly appreciated. The code is rough right now as I just have everything thrown into the controller. Some structure will come later.

HTML

<div ng-controller="mainController" class="col-md-5 col-md-offset-5">
    <div>        
{{quizQuestions}}
    </div>
    <div ng-repeat="answers in quizAnswers">
        <label>{{answers}}</label>
        <input class="rad" type="radio" name="answer" ng-click="markAnswer($index)">
    </div>
    <div>
        <label>Change the question</label>
        <input type="button" ng-click="decrease()" value="Back">
        <input type="button" ng-click="increase()" value="Next">
    </div>
</div>

Angular

$scope.adder = 0;
$scope.answer = [];

$scope.markAnswer = function(index) {
        $scope.answer.splice($scope.adder,1,index);
    };

$scope.display = function(number) {
    $scope.quizQuestions = allQuestions[number].question;
    $scope.quizAnswers = allQuestions[number].choices;
};

$scope.decrease = function() {
    if($scope.adder === 0) {
    } else {
        $scope.adder -= 1;
        $scope.display($scope.adder);
    }
    document.getElementsByClassName('rad')      [$scope.answer[$scope.adder]].checked = true;
};
$scope.display($scope.adder);

There is a syntax error in your "rad" class ng-click

<input class="rad" type="radio" name="answer" ng- click="markAnswer($index)">

you need to take out the space between ng- and click

For what your doing, you should look into the ng-model directive. Mind if take a look at your markAnswer() function?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM