简体   繁体   中英

Get index of row in table using angularJS

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

you can use $index

   <tr ng-repeat = "cust in costomers">
     <td> {{$index}} </td>
  </tr>

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>

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM