如何通过$index值来获取ng中的元素repeat

How to get an element within an ng-repeat by its $index value

本文关键字:ng 元素 repeat 获取 何通过 index      更新时间:2023-09-26

我使用ng repeat,但如果迭代满足某些条件,我想修改迭代。我的问题是,获得应该修改的特定迭代的最佳方法是什么?

目前,我已经使用:第n个子选择器进行了操作,但我想知道是否有一种更角度的方法可以使用$index或任何其他更角度的方式来实现这一点?

HTML代码段:

<div class="line_row" ng-repeat="x in program">
    {{x.current_state}
</div>

JS代码段:

for (j = 0; j < $scope.program.length; j++) {
    if ($scope.reader_location[j] == someCondition) {
        // this is the line that I'm interested in replacing.
        $(".line_row:nth-child("+(j+1)+")").css("background-color","red") 
    }
}

我认为您可以在这里根据表达式求值ng-class,它将在该元素上放置一个类。

HTML

<div class="line_row" ng-repeat="x in program" ng-class="{red: methodCall(x)}">
    {{x.current_state}}
</div>

代码

$scope.methodCall = function(x){
   return x.current_state == 'something'
}

CSS

.red {
   background-color: "red"
}

您可以将ng-class与条件一起使用。如果ng-class的表达式为true,它将添加一个CSS类,在这种情况下,我将其命名为redbackground

HTML

<div class="line_row" ng-repeat="x in program track by $index" 
                      ng-class="{redbackground: $index === someCondition}">
  {{x.current_state}
</div>

CSS

.redbackground { background: red; }

下面是一个如何以多种不同方式使用ng类的教程。