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

问题描述

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

我最终会在我的页面上有 5 个 div.

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

解决方案

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

标记:

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

控制器

function testCtrl($scope) {$scope.data = {prop1: 'a',prop2: 'b',prop3: 'c',道具4:'c'}}

输出:

0 - prop1 - a1 - prop2 - b2 - prop3 - c3 - prop4 - c

请参阅此 fiddle 以供参考

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.

解决方案

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

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

10-31 22:15