7

I want to get index of each row in this table using angularJS

<table>
<tbody>
  <tr ng-repeat = "cust in costomers">
     <td> cust.name </td>
     <td> cust.phone </td>
     <td> cust.address </td>
  </tr>
</tbody>

I want to have a variable that contains the index of each row not to just display it

3
  • what does variable that contains the index mean? Explain intended usage Commented Jul 27, 2014 at 13:35
  • Data in each row will be changed according to the need of changing it So instead of sending it to server then receiving it again to display it for the user I want to change it directly without the need of getting it from server each time I change an index of the row Commented Jul 27, 2014 at 14:08
  • don't even need index for that, pass cust as argument to any controller methods. Still not very clear what higher level issue is Commented Jul 27, 2014 at 14:10

4 Answers 4

12

you can use $index

   <tr ng-repeat = "cust in costomers">
     <td> {{$index}} </td>
  </tr>
Sign up to request clarification or add additional context in comments.

Comments

4

I think you should be using the <tr> tag to place your ng-repeat directive. You can use ng-repeat's $index property. See ng-repeat's documentation.

<table>
  <tbody>
    <tr ng-repeat = "cust in costomers">
      <td> {{$index}} </td>
      <td> {{cust.name}} </td>
      <td> {{cust.phone}} </td>
      <td> {{cust.address}} </td>
    </tr>
  </tbody>
</table>

3 Comments

I want to have a variable that contains the index of each row not to just display it
can you tell me your use case in having each item have an index property? perhaps there is another way to solve your problem?
Data in each row will be changed according to the need of changing it So instead of sending it to server then receiving it again to display it for the user I want to change it directly without the need of getting it from server each time I change an index of the row
2

$index works fine when the ng-repeat is not filtered. If you use a filter, it might be better to use indexOf(). Example:

<input type="text" ng-model="filterCustomers" placeholder="search...">
<table>
  <tbody>
    <tr ng-repeat = "cust in costomers | filter:filterCustomers">
      <td> {{costomers.indexOf(cust) + 1}} </td>
    </tr>
  </tbody>
</table>

Comments

1

If you want to use your own variable as index you can use this:

<table>
<tbody>
  <tr ng-repeat = "(index, cust) in costomers">
     <td> {{index}} </td>
     <td> cust.name </td>
     <td> cust.phone </td>
     <td> cust.address </td>
  </tr>
</tbody>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.