javascript - ng-repeat 向一个元素添加条件类

标签 javascript jquery css angularjs angularjs-ng-repeat

我正在构建简单的测验应用程序,我想将 correctwrong 类添加到 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/

相关文章:

javascript - d3复杂数据,更新现有节点

javascript - 刷新时,数组中新添加的元素将从数组列表本身中删除

javascript - 在 ie9 等旧浏览器上使用网络加密

asp.net - CSS 表单、ASP.NET 验证摘要是靠不住的

javascript - 从动态添加的输入中获取数据

javascript - 使用递增 ID 创建动态样式标签

javascript - 列表的响应包装器

javascript - 编辑前后元素的状态(使用 contentEditable)

html - 并排对齐按钮 Bootstrap

html - 选择这个而不是那个