[英]How to access and use index of each item inside ng-repeat
I have a table where the last column in each row contains a little loading icon which I would like to display when a button inside the table is clicked. 我有一个表格,其中每行的最后一列包含一个小的加载图标,我想在单击表格内的按钮时显示该图标。
When each table row is generated with ng-repeat, the loader shows up in every row rather than the individual one. 当使用ng-repeat生成每个表行时,加载器将显示在每一行而不是单个行中。 How can I set ng-show to true or false for only the current index clicked?
如何仅针对当前单击的索引将ng-show设置为true或false?
Template: 模板:
<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>
Controller: 控制器:
$scope.someAction = function(recordName) {
$scope.loading = true;
};
You can pass in the $index
parameter and set/use the corresponding index. 您可以传入
$index
参数并设置/使用相应的索引。 $index
is automatically available in the scope of an ng-repeat
. $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;
};
Here's a generic sample with all the logic in the view for convenience: 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>
There are many ways to handle this. 有很多方法可以解决这个问题。
The problem here is that your variable loading is sharing the scope between the rows. 这里的问题是你的变量加载是在行之间共享范围。
One approach could be use $index 一种方法可以是使用$ index
HTML 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 JS
$scope.someAction = function(recordName, $index) {
$scope.loading[$index] = true;
};
Using a property in your object record: 在对象记录中使用属性:
HTML 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 JS
$scope.someAction = function(record) {
var name = record.name;
record.loading = true;
};
Best regards 最好的祝福
The scope inside ng-repeat is different form the one outside. ng-repeat中的范围与外部的范围不同。 Actually the scope outside ng-repeat is the parent of the one inside.
实际上,ng-repeat之外的范围是内部范围的父级。 So the html code goes here
所以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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.