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

Javascript 如何访问和使用ng repeat中每个项目的索引,javascript,angularjs,angularjs-ng-repeat,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.na

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

当使用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>

您可以传入
$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;
};

<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>

点击我!项目值:{{foo}}

项{{$index}正在加载


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

这里的问题是,变量加载在行之间共享作用域

可以使用一种方法

HTML

在对象记录中使用属性:

HTML


最好的问候

ng repeat内部的范围与外部的范围不同。实际上,ng repeat外部的范围是内部范围的父范围。所以html代码在这里

<tr ng-repeat="record in records">
    <td>{{ record.name }}</td>
    <td><a ng-click="someAction(record)">Some Action</a></td>
    <td ng-show="$parent.loading">Loading...</td>
</tr>

{{record.name}
一些行动
加载。。。

它很好地传入了索引,但是当它到达
$scope.loading[$index]=true
时,我得到
无法设置未定义的
@greg的属性“1”,因为您需要使
$scope.loading
成为一个数组。参见我的通用示例。我刚刚在视图中将其初始化为数组。否则,进入控制器并放入
$scope.loading=[]
,这样您就有了存储标志的位置。第一种方法无法工作,但第二种方法工作得很好。谢谢@格雷格,我真的建议你弄清楚如何使用
$index
。我不介意回答更多关于它的问题。您不应该像这样向数据中添加属性。这最终可能会导致更多的问题。想象一下,如果需要将
记录
保存到数据库中,现在每个项都有与视图关联的属性,因此需要删除。将视图和模型问题分开。为什么我有一个问题这是我的代码:
<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>
$scope.someAction = function(recordName, $index) {
    $scope.loading[$index] = true;
};
<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>
$scope.someAction = function(record) {
   var name = record.name; 
   record.loading = true;
};
<tr ng-repeat="record in records">
    <td>{{ record.name }}</td>
    <td><a ng-click="someAction(record)">Some Action</a></td>
    <td ng-show="$parent.loading">Loading...</td>
</tr>