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

Adjusting the font color when hovering over multiline text

I am currently in the process of coding a website for my job, and I am working on changing the text color when it is hovered over. However, there seems to be a break in my code causing the text not to highlight all at once. Any guidance or suggestions on h ...

How to Insert <ul></ul> After Every Other <li> Element Using Angular's ngRepeat

With my current setup, I have a list item (li) within a list (ul) and applied ngRepeart. However, I would like to create a new ul after every 2nd li. Is this possible with AngularJS? <ul> <li>simth</li> <li>aryan</li> < ...

Interactive image sliders in a Netflix-inspired style with live previews on hover, fully compatible with Bootstrap framework

I'm looking for suggestions on Twitter Bootstrap compatible jquery plugins that can create a Netflix-style continuously scrolling image carousel with mouse-over functionality. I've tried the carousel included in the Bootstrap JS library, but it r ...

How to verify the parent nodes in a jstree

I have implemented a two state jstree. However, I am encountering an issue where it is not possible to select any other node in relation to a node. My goal is that when I click on a specific node, all of its parent nodes should also be checked. Any assist ...

effectively showcasing information in a datatable by converting JSON data into objects

I am looking for a way to display balance information in datatables, but I have not been able to find a solution yet. <!DOCTYPE html> <html lang="en"> <head> <title>Comment</title> <meta charset="u ...

What is the best method for updating the state of a dynamically created Switch component using React's setState()?

I have a dynamic creation of Switches based on a map like shown in the image: https://i.stack.imgur.com/jDLbS.png For example, using this code: const [enabled, setEnabled] = useState(false) return( ... {people.map((person) => ( ... ...

The application suddenly displays a blank white screen after encapsulating my layout with a context provider

Here is the custom layout I created: export const metadata = { title: "Web App", description: "First Project in Next.js", }; export default function CustomLayout({ children }) { return ( <html lang="en"> ...

Using $state outside of the AngularJS environment

Currently, I am working on an AngularJS application that is meant to be a hybrid mobile app for both android and iOS platforms. Within the project, there is a JavaScript file that does not belong to any module. In this particular JavaScript file, I need to ...

Unable to retrieve innerHTML from a jQuery element

My current task involves implementing the Google Maps API. The code snippet below is what I have written so far: <div id="map"></div> To inspect the content of $("div#map"), I am utilizing the Google Chrome console. console.log($("div#map")) ...

Create PDFs using PhantomJS when the HTML content is fully loaded and ready

I am a newcomer to utilizing phantomjs and encountering difficulties in rendering my website as a PDF file. Although I can successfully render a simple version of the page, issues arise when multiple images and web fonts are involved, causing the DOM not t ...

State properties in Vuex remain unchangeable despite using mutator methods

I've encountered an issue with the code in my vuex module called user.js: import Vue from "vue"; import Vuex from 'vuex'; Vue.use(Vuex); const state = { user: { firstName: null, lastName: null, ...

Toggle class on child element when parent is clicked

I am currently working on a functional React component that looks like this: const RefreshButton = () => ( <IconButton> <RefreshIcon /> </IconButton> ) My goal is to dynamically assign a class attribute ...

The client side script "/socket.io/socket.io.js" was not located, therefore the Express-generator project was used instead

I have been working on integrating the "chat-example" from Socket.IO's official website into an Express-generator generated project while keeping the structure of the project intact. I have made minimal changes to the code to fit it into the existing ...

JavaScript opacity adjustments not achieving desired outcome

My attempt to make this sub menu fade in and out upon button press is not working as expected. It should fully fade in shortly after clicking 'help' and completely fade out when clicking 'back'. Is the problem with the method I'm u ...

How can you switch between CSS styles using JQuery?

Is there a way to change CSS properties every time I click using jQuery? I couldn't find any information on this specific topic. Can someone guide me on how to achieve this with jQuery? I want the background color to change each time it is clicked. W ...

Troubleshooting Display Issue with Nested Div Selection in jQuery Tooltips

I have a long list of data consisting of 30-50 rows, each row needing its own distinct tooltip. Creating unique IDs for each row would require unnecessary JavaScript code. My goal is to utilize jQuery to retrieve the tooltip from the nested <DIV> wit ...

Obtain non-numeric parameters from the URL in Angular 2 by subscribing to

How do I handle subscribing to a non-numeric parameter from a URL? Can the local variable inside my lambda function params => {} only be a number? Here's my code: getRecordDetail() { this.sub = this.activatedRoute.params.subscribe( ...

Vue appears to be having trouble waiting for the axios Post request

While testing a login request, I encountered an issue where jest did not call the mock: This is my test : const User = '123123' jest.mock('axios', () => ({ get: jest.fn(), post: (_url, _body) => new Promise((resolve, reject ...

Conceal a list of items within a div that has a particular class

This is a sample of my HTML code: <div class="row"> <div class="col-md-12"> <div class="scrollbox list"> <ul class="list-unstyled"> <li id="articulate.flute">articulate flut ...

Issue: AngularJS Injector Module Error

Recently started learning angularjs and trying to set up an app. Here's a simple and direct way to do it: Angular controller: (function () { 'use strict'; angular .module('myQuotesApp') .controller(' ...