重复一个对象时,如何在ng-repeat中获取元素的$ index?

时间:2022-09-08 20:31:40

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

我知道对象值没有索引,但我说我有一个名为foo的对象有5个键,我这样做:

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

I will end up with 5 divs on my page.

我最终会在我的页面上显示5个div。

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.

我的问题是我怎么问Angular,“嘿,哪个div是这个?它是第一个吗?它是第二个吗?请给我一个号码。”我不能使用{{$ index}},因为对象没有索引。我不能使用{{$ id}},因为它似乎给出一个从5开始的数字,并且总是很奇怪......有时候。我只是想知道在重复一个对象而不是一个数组时我在ng-repeat中的位置。

2 个解决方案

#1


1  

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

重复非数组对象时,您仍然可以使用{{$ index}}。

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


1  

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.

不幸的是,没有办法让你的位置在除$ index之外的ng-repeat循环中,并且只适用于数组。因此,一种可能的解决方案是在使用之前将对象解压缩为数组。如果angular想要一个数组,请给它一个。

#1


1  

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

重复非数组对象时,您仍然可以使用{{$ index}}。

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


1  

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.

不幸的是,没有办法让你的位置在除$ index之外的ng-repeat循环中,并且只适用于数组。因此,一种可能的解决方案是在使用之前将对象解压缩为数组。如果angular想要一个数组,请给它一个。