0

I am building simple quiz app and I want to add correct or wrong class to element inside ng-repeat for CSS styling purposes.

JS:

$scope.checkAnswer = function (answer) {
        if (answer == $scope.answer)
        {
            $scope.score++;
            $scope.correctAns = true;
            $scope.nextQuestion();
            
        } else {
            $scope.correctAns = false;
        }
    };

I was trying to use ng-class expression with no luck:

<ul id="options">
  <li ng-repeat="option in options" id="answer_{{$index}}" ng-class="{'correct' : correctAns, 'wrong' : !correctAns}">
    <img data-id="{{$index}}" ng-src="{{img[$index]}}" ng-click="checkAnswer({{$index}})">
  </li>
</ul>

This conditional assigns "correct" to all elements in my list. I want to add this class only to one that is really correct.

asontu
  • 4,548
  • 1
  • 21
  • 29
Mateusz Wójt
  • 109
  • 2
  • 15
  • 1
    `checkAnswer($index)` or `checkAnswer(option)`, and `"{'correct' : option == $scope.answer}"`, storing to variable will make every item same. – YOU Mar 23 '15 at 15:04
  • how about using ng-show if the value of $scope.correctAns = true; as in ng-show="correctAns==true"? – Jax Mar 23 '15 at 15:16

2 Answers2

0

"ng-repeat" - directive uses "isolated scope" aspect which means that it shadows (copy to local scope) your primitive ‘correctAns’ variable and if you try to modify it from the local scope which actually you do then the parent scope value won’t be changed. You have the following solution: Don't use primitive value, use object.property instead - in your case it could be answer.correct

Please check detailed answer below:Directive isolate scope with ng-repeat scope in AngularJS

Community
  • 1
  • 1
Yuriy Anisimov
  • 825
  • 1
  • 7
  • 16
0

This is my example bases on how I understand the requirement. Hope it can help.

https://jsfiddle.net/5zoh6L7d/

I have "class" information for each option, like that:

  $scope.options = [
    {key: 1, value: "Earth", class: ""},
    {key: 2, value: "Fire", class: ""},
    {key: 3, value: "Air", class: ""},
    {key: 4, value: "Water", class: ""},
  ];

When user select an answer, I check it and change the "class" of selected answer.

Hieu TB
  • 162
  • 5