本文介绍了在对象上重复时,如何获取ng-repeat中element的$ index?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我将在页面上显示5个div.

I will end up with 5 divs on my page.

我的问题是我如何问Angular:嘿,这是哪个div?是第一个吗?是第二个吗?请给我一个数字."我不能使用{{$index}},因为对象没有索引.我不能使用{{$id}},因为它似乎给出了一个从5开始的数字,并且总是奇数...有时.我只想知道在对象而不是数组上重复ng-repeat的位置.

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.

推荐答案

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

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

标记:

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

控制器

function testCtrl($scope) {

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

}

输出:

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

请参见小提琴以供参考

这篇关于在对象上重复时,如何获取ng-repeat中element的$ index?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 22:15