1

I have a page where An array has an array inside it and is displyed using ng-repeat 2 times.

<div ng-repeat="chapter in chapters">
        <div ng-repeat="page in chapter.pages">
            <p>Title: {{page.title}}</p>
        </div>
    </div>

the array is:

$scope.chapters= [
    {
        pages: [
            {title: 'Title3'},
            {title: 'Title4'},
            {title: 'Title5'}
        ]
    },
    {
        pages: [
            {title: 'Title1'},
            {title: 'Title2'}
        ]
    }

];

I need to access $index of chapter and pages inside 'p' element i.e. i want to access the chapter no and page no there.

how can i achieve that?

raj
  • 694
  • 1
  • 5
  • 22

2 Answers2

3

The key here is the $index variable provided within each ng-repeat directive. Note that the index starts from 0, that's why I added + 1 in displaying the chapters and pages.

<div ng-repeat="chapter in chapters" ng-init="chapterNumber = $index">
    <div ng-repeat="page in chapter.pages">
        <p>Chapter: {{chapterNumber + 1}}, Page: {{$index + 1}}, Title: {{page.title}}</p>
    </div>
</div>

JSFiddle

khakiout
  • 2,372
  • 25
  • 32
0

for chapter use {{$index}} for page you can access index using {{$parent.$index}}
please see here: http://jsbin.com/xowub/2/

 <div ng-repeat="chapter in chapters">
            <div ng-repeat="page in chapter.pages">
                <p>Page: {{$parent.$index}}  chapter:{{$index}} Title: {{page.title}}</p>
            </d
          </div>
sylwester
  • 16,498
  • 1
  • 25
  • 33
  • No, please don't use `$parent`, please read https://docs.angularjs.org/api/ng/directive/ngInit instead. – ivarni Aug 06 '14 at 10:35
  • 1
    @ivarni what is the problem with $parent ? – sylwester Aug 06 '14 at 10:37
  • 1
    because by referring to `$parent` you make assumptions about the scope hierarchy. There's a good reason why the angular team introduced `ng-init` for the sole purpose of solving the issue OP is having. – ivarni Aug 06 '14 at 10:49
  • @ivarni hmm.. so is chapter a parent of page or not ? – sylwester Aug 06 '14 at 10:58
  • It is right now. It might not be in 2 months when someone adds an isolated directive between the two repeats. Look, I'm not here to have an argument. If you or the OP really want to experience what eventually happens when you rely on `$parent`, feel free. – ivarni Aug 06 '14 at 11:18