我正在构建简单的测验应用程序,我想将 correct
或 wrong
类添加到 ng-repeat
内的元素以用于 CSS 样式设置。
JS:
$scope.checkAnswer = function (answer) {
if (answer == $scope.answer)
{
$scope.score++;
$scope.correctAns = true;
$scope.nextQuestion();
} else {
$scope.correctAns = false;
}
};
我尝试使用 ng-class
表达式,但没有成功:
<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>
此条件将“正确”分配给我列表中的所有元素。我只想将此类添加到真正正确的类中。
最佳答案
“ng-repeat” - 指令使用“隔离范围”方面,这意味着它隐藏(复制到本地范围)您的原始“correctAns”变量,如果您尝试从本地范围修改它,那么您实际上是这样做的父范围值不会更改。您有以下解决方案: 不要使用原始值,而是使用 object.property - 在你的情况下它可能是 answer.correct
请查看下面的详细答案:Directive isolate scope with ng-repeat scope in AngularJS
关于javascript - ng-repeat 向一个元素添加条件类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29213525/