How can you retrieve the index of the outer repeater item within nested ng-repeaters in AngularJS?

If I have multiple ng-repeat loops nested within each other like in the following example:

<div ng-repeat="outeritem in outerobject">

    <div ng-repeat="inneritem in innerobject" ng-click="function(inneritem.key, $index)"></div>

<div>

How can I access the $index value from the outterobject loop inside the function(inneritem.key, $index) function that is inside the ng-click directive of the innerobject loop?

Update:

I ultimately decided to implement this approach, despite there being two other viable solutions mentioned in the comments below.

<div ng-repeat="(indexvalue, outeritem) in outerobject">

    <div ng-repeat="inneritem in innerobject" ng-click="function(inneritem.key, indexvalue)"></div>

<div>

Answer №1

To access the scope of the parent element, you can utilize $parent.

ng-click="function(inneritem.key, $parent.$index)"

Answer №2

One effective method is to use ng-init properly:

<div ng-repeat = "outerItem in outerObject" 
     ng-init = "outerIndex=$index">

    <div ng-repeat = "innerItem in innerObject" 
         ng-click = "expression($index, outerIndex)"></div>

<div>

By utilizing ng-init, the value of $index from the outer scope created by the outer ng-repeat directive can be accessed.

It's crucial to place ng-init correctly to retrieve values on the appropriate scope. This means that placing it beside the second ng-repeat would capture the index of that specific repeater rather than the outer one!

Remember that any expression defining outerIndex on a child scope won't affect the one on the parent scope. To prevent this, opt for an object property like outer.Index.

This method is resilient to code changes impacting $parent scopes, making it more reliable, especially when nested within directives like ng-repeat.

In addition, testing this approach is straightforward compared to using $parent.


The official Angular documentation for ng-init acknowledges this as "the only appropriate use of it":

The only appropriate use of ngInit is for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope.

Answer №3

Another approach is to utilize ng-init and define it directly

<div ng-repeat="item in object">

    <div ng-init='index=$index' ng-repeat="nestedItem in nestedObject" ng-click="executeFunction(nestedItem.key, index)"></div>

<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

The issue arises when attempting to update the input of a child component within a reactive form during the OnInit lifecycle

My dilemma arises in working with data stored in the ngrx entity store, as it gets displayed in chunks based on pagination. The issue lies with rxjs somehow remembering the paging history. For instance, when I fetch the first page of data from the server, ...

Exploring the capabilities of VueJs in detecting events triggered by parent components

When users click on a specific image in the Collection(parent component), my goal is to display that image in a Modal(child component). Below is the code snippet: routes.js import Home from './components/Home'; import About from './compone ...

What are the steps to take when dealing with ERR_INSECURE_RESPONSE?

When utilizing my AngularJS application, I encounter an issue when using $http.get() with https urls that have self-signed certificates. The problem arises when Chrome rejects the request and logs an error message ERR_INSECURE_RESPONSE in the console. I a ...

Seeking assistance for my dissertation assignment: electron, express, and SQLite3

I am currently dedicated to my thesis project, which involves designing an educational desktop video game for both public and private schools within my city. Being a fan of electron, I thought it would be a great idea to develop my app using this platform ...

Initially, calling angular.element(..).scope() will return undefined

I have encountered an issue where I am unable to access my angular controller's scope outside of the controller. This problem arises when using an external JavaScript library that performs certain actions and executes callbacks upon completion. In one ...

Retrieve a result following an AJAX post request to utilize the obtained value in subsequent code functionalities

Below is the code snippet where an "if" statement is used to check if a query has been executed correctly. If it has, a part of the script is stored in a variable called $output. This variable is then immediately read by the notification script included in ...

What is the best way to showcase the properties of multiple files with the help of

I have been attempting to utilize jQuery to exhibit the specifics of several uploaded files. Below is my code: <!DOCTYPE html> <html> <head> <title>jQuery Multi File Upload</title> </head> <body> <f ...

A step-by-step guide on incorporating the C3 Gauge Chart into an Angular 5 application

I have been attempting to incorporate the C3 Gauge Chart from this link into a new Angular 5 application. Below is my code within chart.component.ts : import { Component, OnInit, AfterViewInit } from '@angular/core'; import * as c3 from &apos ...

What is the best way to swap out an observable array with an array retrieved from an API response

I have a custom material autocomplete input that allows users to select items in a dynamic form component. Since the fields of the form are dynamic, I need to filter the list of items every time a user types something into the input. filteredOptions: { [k ...

Is it possible to implement pagination for API requests in a JavaScript and React environment?

I am currently working on an app that fetches data from a movie API and returns 20 items from page 1. I am now looking to implement pagination so that users can click a button to view more items from subsequent pages. Below is my current API call: export ...

Exploring JQuery and JavaScript for loop guide

Currently working on a small application where users are required to input information, and I am implementing text hints in the input fields. However, I have encountered an issue when using a for loop in my code. Oddly enough, the text hints display corre ...

Reset the form value in React using Material UI components

Currently, I am working with React Material and hooks, attempting to reset a material form. However, despite my efforts to adjust the state, I am not seeing any changes reflected. <form className="create-account-form" autoComplete="off" onSubmit={onSub ...

Under what circumstances would you need to manually specify the displayName of a React component?

After coming across an article (linked here: https://medium.com/@stevemao/do-not-use-anonymous-functions-to-construct-react-functional-components-c5408ec8f4c7) discussing the drawbacks of creating React components with arrow functions, particularly regardi ...

Using a nested loop in Javascript to fetch JSON data

My goal is to display Categories and their corresponding subcategories in a specific order. However, my current method of using loops within loops is not producing the desired outcome: Category(Mobile) Category(Laptop) Subcategory(Iphone4) Subcategory(Iph ...

Using JavaScript in PHP files to create a box shadow effect while scrolling may not produce the desired result

Issue at hand : My JavaScript is not functioning properly in my .php files CSS not applying while scrolling *CSS Files are named "var.css" #kepala { padding: 10px; top: 0px; left: 0px; right: 0px; position: fixed; background - c ...

Using regex in Javascript to find and match an ID within a string

JavaScript: var data='<div id="hai">this is div</div>'; I am looking to retrieve only the ID "hai" using a regular expression in JavaScript. The expected output should be, var id = regularexpression(data); The variable id should n ...

Monitor the current playing status of a YouTube video across any webpage

I am interested in developing a web extension that can identify the playback status of all YouTube videos visited by a user. Upon researching the YouTube API, I discovered that it only allows access to videos that are embedded by me. In this case, I am not ...

What strategies can be implemented to improve the total blocking time in Vue for optimal performance

I'm facing a challenge that I can't seem to resolve. My page has a high total blocking time (2+ sec). Despite trying to load every vue component asynchronously, the issue persists with 2+ sec TBT. I'm puzzled by what could be causing such a ...

Tips for handling data strings using axios

In my node.js project, I am following a manual and attempting to display data obtained from jsonplaceholder app.get('/posts', async (req, res) => { const response = await axios.get('https://jsonplaceholder.typicode.com/posts'); ...

Use jQuery's .each method to reiterate through only the initial 5 elements

Is there a way to loop through just the initial 5 elements using jQuery's each method? $(".kltat").each(function() { // Restrict this to only the first five elements of the .kltat class } ...