Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-change not firing after click on each radio button in a list

I am creating a small application for my college project, I have a scenario where when the user clicks on a radio button an event should be fired.

My Angular code block:

<div ng-repeat="q in questionList " ng-if="ExamOver == false">
      <h2>{{count+1}} .{{q.questionText}}</h2>
      <ul>
          <li ng-repeat="d in q.Choices">
              <input type="radio" name="isCorrect" ng-model="correctAnswer.isworking" ng-change="getDetails($index,d,correctAnswer.isCorrect);" value="Yes" />
              {{d.choiceText}}
          </li>
     </ul>
</div>

In my controller, I have this code:

$scope.correctAnswer = {isCorrect : false};

$scope.getDetails = function (index, choiceList, isCorrect) {    
    /* some logic... */
}

The events are firing only once per button, I am trying to work around this for past few hours without any progress, can someone please guide me what I am doing wrong here?

like image 421
A.Bi Avatar asked Apr 26 '17 06:04

A.Bi


2 Answers

ngChange gets triggered if the value of ngModel changes.

Your radio buttons all have the same value namely "Yes"

<input type="radio" name="isCorrect" ng-model="..." ng-change="..." value="Yes" >
like image 191
Giovani Vercauteren Avatar answered Oct 25 '22 05:10

Giovani Vercauteren


ng-change will be fired when the value of the variable you binded (with ng-model) changed. Here, all your radio buttons have the same value="Yes". That's is why ng-change is not triggered. From docs:

Evaluate the given expression when the user changes the input. The expression is evaluated immediately, unlike the JavaScript onchange event which only triggers at the end of a change (usually, when the user leaves the form element or presses the return key).

The good solution depends of your needs, but where are some ideas:

Solution 1

Set different values for your inputs:

<li ng-repeat="d in q.Choices">
     <input type="radio" 
            name="isCorrect" 
            ng-model="correctAnswer.isworking" 
            ng-change="getDetails($index, d, correctAnswer.isCorrect)" 
            ng-value="$index" />
     {{d.choiceText}}
</li>

Solution 2

Fire your function whenever a radio is clicked:

ng-click="getDetails($index, d, correctAnswer.isCorrect)"
like image 30
Mistalis Avatar answered Oct 25 '22 06:10

Mistalis