【问题标题】:How to access and use index of each item inside ng-repeat如何访问和使用 ng-repeat 中每个项目的索引
【发布时间】:2015-01-13 01:56:48
【问题描述】:

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

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

控制器:

$scope.someAction = function(recordName) {
  $scope.loading = true;
};

【问题讨论】:

标签: javascript angularjs angularjs-ng-repeat


【解决方案1】:

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

为方便起见,这是一个包含所有逻辑的通用示例:Live demo (click).

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

【讨论】:

  • 它在索引中的传递很好,但是当它到达$scope.loading[$index] = true 我得到Cannot set property '1' of undefined
  • @greg 因为您需要将 $scope.loading 设为一个数组。请参阅我的通用示例。我只是在视图中将它初始化为一个数组。否则,请进入您的控制器并输入$scope.loading = [],以便您有一个存储标志的地方。
【解决方案2】:

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

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

一种方法可以使用$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>

JS

$scope.someAction = function(recordName, $index) {
    $scope.loading[$index] = true;
};

在对象记录中使用属性:

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>

JS

$scope.someAction = function(record) {
   var name = record.name; 
   record.loading = true;
};

最好的问候

【讨论】:

  • 第一种方法无法正常工作,但第二种方法效果很好。谢谢!
  • @greg 我真的建议你弄清楚如何使用$index。我不介意回答更多关于它的问题。您不应该像这样向您的数据添加属性。这可能最终会导致更多问题。想象一下,如果您需要将records 保存到数据库 - 现在每个项目都有将其与视图关联的属性,因此需要将其删除。将您的视图和模型关注点分开。
【解决方案3】:

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>

【讨论】:

    猜你喜欢
    • 2013-01-26
    • 2015-06-19
    • 1970-01-01
    • 1970-01-01
    • 2015-12-10
    • 2013-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多