How do I get the $index of element in an ng-repeat when repeating over an object?

 ̄綄美尐妖づ 提交于 2019-12-12 20:23:55

问题


I know object values don't have indexes but say I have an object named foo with 5 keys and I do:

<div ng-repeat="(key,value) in foo">

I will end up with 5 divs on my page.

My question is how do I ask Angular, "Hey, which div is this? Is it the first one? Is it the second one? Give me a number please." I can't use {{$index}} because objects don't have indexes. I can't use {{$id}} because it seems to give a number that starts from 5 and is always odd... sometimes. I just want to know where in the ng-repeat I am when repeating over an object and not an array.


回答1:


You could still use {{$index}} when repeating non array objects.

Markup:

<div ng-app>
  <div ng-controller="testCtrl">
    <div ng-repeat="(key, value) in data">
      <span>{{$index}} -</span>
      <span>{{key}} -</span>
      <span>{{value}}</span>
    </div>
  </div>
</div>

Controller

function testCtrl($scope) {

  $scope.data = {
    prop1: 'a',
    prop2: 'b',
    prop3: 'c',
    prop4: 'c'
  }

}

Output:

0 - prop1 - a
1 - prop2 - b
2 - prop3 - c
3 - prop4 - c

See this fiddle for your reference




回答2:


Unfortunately no, there just isn't a way to get your position in an ng-repeat loop other than $index and that only works for arrays. So one possible solution is to just unzip you object into an array before using it. If angular wants an array, give it one.



来源:https://stackoverflow.com/questions/37934670/how-do-i-get-the-index-of-element-in-an-ng-repeat-when-repeating-over-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!