Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS problems with radio button not selecting

I'm trying to catch the ng-change event on a radio button, but the problem is that it only gets checked when I click for second time on any of the radios in the same group. Also, when I click on a radio for first time, ng-changed gets called, but it doesn't if I click again in another radio button or in the same one.

<div>
<div ng-repeat="element in questions" ng-class="{'in':$first,'hidden': !$first}">
    <h1>{{element.question}}</h1>
    <div>
        <input type="radio" name="answer" ng-value="A" ng-model="$parent.answer" ng-change="enableSubmit()">{{element.answerA}}</input>
        <input type="radio" name="answer" ng-value="B" ng-model="$parent.answer" ng-change="enableSubmit()">{{element.answerB}}</input>
        <input type="radio" name="answer" ng-value="C" ng-model="$parent.answer" ng-change="enableSubmit()">{{element.answerC}}</input>
    </div>
</div>
<button id="prev" class="hidden" ng-click="prevQuestion()">Anterior</button>
<button id="next" ng-click="nextQuestion()" disabled>Siguiente</button>
</div>

What could be wrong with this? Thanks in advance.

like image 548
Xabi Avatar asked May 31 '26 14:05

Xabi


1 Answers

Since ng-repeat creates its own $scope, as you can see in this answer, you must use, preferably, controller-as-syntax to achieve what you want.

A demo working with your code:

DEMO

Note: I don't know if you're using jQuery for something else besides hide/disable buttons, but all that things can be easily done with Angular, like this:

<input type="radio" ng-model="main.answer" value="A" ng-change="enableSubmit()" />

$scope.enableSubmit = function() {
    $('#next').prop('disabled', false);
};

Should be just this in view:

<button ng-disabled="!main.answer" id="next" ng-click="nextQuestion()">Siguiente</button>

I hope it helps!

like image 51
developer033 Avatar answered Jun 02 '26 20:06

developer033



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!