如何访问和使用ng-repeat中每个项目的索引

gre*_*reg 9 javascript angularjs angularjs-ng-repeat

我有一个表格,其中每行的最后一列包含一个小的加载图标,我想在单击表格内的按钮时显示该图标.

当使用ng-repeat生成每个表行时,加载器将显示在每一行而不是单独的一行中.如何仅针对当前单击的索引将ng-show设置为true或false?

模板:

<tr ng-repeat="record in records">
  <td>{{ record.name }}</td>
  <td><a ng-click="someAction(record.name)">Some Action</a></td>
  <td ng-show="loading">Loading...</td>
</tr>
Run Code Online (Sandbox Code Playgroud)

控制器:

$scope.someAction = function(recordName) {
  $scope.loading = true;
};
Run Code Online (Sandbox Code Playgroud)

m59*_*m59 19

您可以传入$index参数并设置/使用相应的索引.$index在一个范围内自动可用ng-repeat.

<td><a ng-click="someAction(record.name, $index)">Some Action</a></td>
<td ng-show="loading[$index]">Loading...</td>


$scope.someAction = function(recordName, $index) {
  $scope.loading[$index] = true;
};
Run Code Online (Sandbox Code Playgroud)

这是一个通用示例,为方便起见,视图中包含所有逻辑:现场演示(单击).

<div ng-repeat="foo in ['a','b','c']" ng-init="loading=[]">
  <p ng-click="loading[$index]=true">Click me! Item Value: {{foo}}<p>
  <p ng-show="loading[$index]">Item {{$index}} loading...</p>
</div>
Run Code Online (Sandbox Code Playgroud)

  • @greg因为你需要使`$ scope.loading`成为一个数组.看我的通用样本.我只是在视图中将其初始化为数组.否则,进入你的控制器并放入`$ scope.loading = []`,这样你就有了存放标志的地方. (3认同)

Sal*_*BFM 5

有很多方法可以解决这个问题.

这里的问题是你的变量加载是在行之间共享范围.

一种方法可以是使用$ index

HTML

<tr ng-repeat="record in records">
    <td>{{ record.name }}</td>
    <td><a ng-click="someAction(record.name, $index)">Some Action</a></td>
    <td ng-show="loading">Loading...</td>
</tr>
Run Code Online (Sandbox Code Playgroud)

JS

$scope.someAction = function(recordName, $index) {
    $scope.loading[$index] = true;
};
Run Code Online (Sandbox Code Playgroud)

在对象记录中使用属性:

HTML

<tr ng-repeat="record in records">
    <td>{{ record.name }}</td>
    <td><a ng-click="someAction(record)">Some Action</a></td>
    <td ng-show="record.loading">Loading...</td>
</tr>
Run Code Online (Sandbox Code Playgroud)

JS

$scope.someAction = function(record) {
   var name = record.name; 
   record.loading = true;
};
Run Code Online (Sandbox Code Playgroud)

最好的祝福

  • @greg我真的建议你弄清楚如何使用`$ index`.我不介意回答更多关于它的问题.您不应该像这样向您的数据添加属性.这可能最终会导致更多问题.想象一下,如果你需要将`records`保存到数据库中 - 现在每个项目都有将其与视图相关联的属性,因此需要将其删除.将您的视图和模型问题分开. (3认同)