How to retrieve the index of a nested ng-repeat within another ng-repeat loop

On my page, there is an array containing nested arrays that are being displayed using ng-repeat twice.

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

The array looks like this:

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

I want to be able to access the $index of each chapter and page within the 'p' element. How can I achieve this?

Answer №1

The important aspect to note is the utilization of the $index variable within the ng-repeat directive. It's crucial to remember that the indexing begins at 0, which is why adding + 1 when displaying the chapters and pages is necessary.

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

Check out the code on JSFiddle

Answer №2

When referencing chapters, use {{$index}}, and for accessing index of pages, use {{$parent.$index}}.
For more information, visit: 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using jQuery to fetch data asynchronously

I am currently dealing with a web application that needs to carry out the following task. It must send GET requests to a web service for each date within a selected date range, yet this process can be time-consuming. Since I plan to visualize the retrieved ...

Utilizing HTML documents instead of images in Owl Carousel 2

I am currently utilizing owl carousel 2 to construct a basic sliding carousel. However, I am only using images at the moment and would like to incorporate HTML files instead. These HTML files contain multiple divs where images can be inserted, and instead ...

react: implement custom context menu on videojs

Can someone assist me with adding a quality selector and disabling the right-click option in a webpage that uses videojs? I am unsure about using plugins, as there were no examples provided in react. Any guidance would be appreciated. VideoPlayer.js impor ...

Is it possible to include an if/else statement within a tailwind class in React components?

I want to dynamically change the background color of a div based on a condition. If the condition is true, I want the background color to be white; otherwise, I want it to be black. Despite trying to achieve this using an if/else statement, the background ...

Can someone clarify the meaning of (e) in Javascript/jQuery code?

Recently, I've been delving into the world of JavaScript and jQuery to master the art of creating functions. I've noticed that many functions include an (e) in brackets. Allow me to demonstrate with an example: $(this).click(function(e) { // ...

How can I ensure the screen is cleared before the next frame in three.js?

While working in Three.js WebGLRenderer, I understand that using context.clearRect() requires a canvas and other elements. However, my question is: How can I achieve the same functionality as clearRect in Three.js WebGLRenderer? In my game, a JSON model i ...

The custom caching strategy was not implemented for the API response in web-api-2/OWIN

Starting with web-api 2 has presented me with a question: how do I set caching settings? I've created a custom caching-message-handler as shown below (simplified for this post) public class CachingMessageHandler : DelegatingHandler { private void ...

What's the best way to implement two AJAX field validations to prevent button redirection on a website?

Can anyone provide guidance on how to implement two ajax field validations for a button to prevent clicking if the data already exists or redirecting to the same page? I am seeking assistance with this issue. Below is the ajax code snippet: function vali ...

Utilize text wrapping to ensure a fixed maximum height for content display

I am in need of a div that contains text spanning multiple lines, with both a fixed width and a maximum height. Currently, I have applied the CSS property overflow: hidden;. However, my issue arises when the last line of text exceeds the maximum height of ...

Explore one of the elements within a tuple

Can we simplify mapping a tuple element in TypeScript? I'm seeking an elegant way to abstract the following task const arr: [string, string][] = [['a', 'b'], ['c', 'd'], ['e', 'f']] const f ...

Reading data from Firestore in Next.js

I came across a Next.js starter that retrieves data from Firestore v9, but it only displays the data after a click event. How can I modify this code in Next.js to automatically show the data without needing to click? import { db } from '@/lib/firebase ...

Methods for breaking down a number into individual elements within an array

Suppose there is a number given: let num = 969 The goal is to separate this number into an array of digits. The first two techniques fail, but the third one succeeds. What makes the third method different from the first two? num + ''.split(&ap ...

Challenge with delayed function execution in AngularJS

In my Angular application, I am encountering a problem in the following scenario. There are three crucial files: MainCtrl.js Upon loading the application, the init() function in MainCtrl.js is triggered, which then calls the flowService as shown below: ...

Issue: Module '../utils/composeObjs' not found after global installation of generator-stencil

Currently, I am in the process of developing a generator for stenciljs which can be found at https://github.com/AkashGutha/generator-stencil Within this project, there is a handy utility function located at the root directory. This function resides in one ...

The iFrame's getFocus function does not activate

I have an iframe set up like this: <iframe name="richTextField" id="richTextField" style="border:#000 1px solid; width:700px; height:300px;"></iframe> I also have some JavaScript code that is supposed to trigger when the iframe gains or loses ...

Encountered an Xpath error while attempting to create a random email generator using Selenium IDE

While attempting to execute a script, I encountered an "element not found" error with Selenium failing to detect the xpath. My goal is to randomly generate email addresses. Every time there is an error message stating: [error] Element .//[@id='GmailA ...

Obtain a specific portion of text from a string that resembles a URL

$("#index-link")[0].search = "?isNameChecked=False&isDateChecked=False&isStatusChecked=True" Is there a way to use jQuery to identify whether isStatusChecked is set to true or false in the given string? ...

Adding quotes is optional when using the append function

We are retrieving product options from the displayed html using variables PRODUCT_CUSTOM_1_ and PRODUCT_NAME_. Some products have quotations like " and '. However, when we post these strings elsewhere, they get cut off at the ". We need to either remo ...

The JSON page does not display the image

I am facing an issue where the images are not displaying on both the JSON page and the HTML page, even though the image source name is being outputted. How can I ensure that the images show up on the HTML page? Thank you for taking the time to help. line ...

Preserve HTML element states upon refreshing the page

On my webpage, I have draggable and resizable DIVs that I want to save the state of so they remain the same after a page refresh. This functionality is seen in features like Facebook chat where open windows remain open even after refreshing the page. Can ...