Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. How can I set ng-show to true or false for only the current index clicked?

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;
};
like image 893
greg Avatar asked Feb 13 '14 00:02

greg


2 Answers

You can pass in the $index parameter and set/use the corresponding index. $index is automatically available in the scope of an 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>
like image 55
m59 Avatar answered Oct 17 '22 14:10

m59


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

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

Using a property in your object record:

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

Best regards

like image 5
SalvadorBFM Avatar answered Oct 17 '22 12:10

SalvadorBFM