Getting two indexes in AngularJS explained

My code includes two ng-repeats for child and parent divs like this:

<div ng-repeat="stage in stages">
  <div ng-repeat="step in steps">
    <button ng-click="clickedStageAndStep($index)">
  </div>
</div>

$scope.clickedStageAndStep = function(index) {
  console.log("Step Index: " + index)
};

I need to extract both the child and parent indexes. How can I achieve that?

Answer №1

Utilize the $parent.$index syntax

Every ng-repeat establishes its own scope and the $index variable pertains to the innermost scope of the respective ng-repeat

$scope.clickedStageAndStep = function(parent, child) {
  console.log("Step Index: " + child);
};
<div ng-repeat="stage in stages">
  <div ng-repeat="step in steps">
    <button ng-click="clickedStageAndStep($parent.$index,$index)"></button>
  </div>
</div>

Note: The closing tag for </button> is missing.

Answer №2

Create a variable to track the parent index


    <div ng-repeat="stage in stages" ng-init="stageNumber = $index">
      <div ng-repeat="step in steps">
          <button ng-click="clickedStageAndStep($index, $parent.$index)" >Click Me</button>
      </div>
    </div>

    $scope.clickedStageAndStep = function(stageIndex, stepIndex) {
      console.log("Step Index: " + stepIndex + " And StageIndex: " + stageIndex)
    };

Answer №3

Try using $parent.$index

Here is the HTML code snippet:

<div ng-app="app" ng-controller="ctrl">
  <div ng-repeat="stage in stages">
    <div ng-repeat="step in stage.steps">
      <span>Index: {{$index}}. ParentIndex:{{$parent.$index}}</span>
    </div>
  </div>
</div>

And here is the JavaScript code snippet:

angular.module('app', []).
controller('ctrl', function($scope) {
  $scope.stages = [{
    steps: ['1', '2', '3']
  }, {
    steps: ['4', '5']
  },
  {steps:['6','7','8']}];
})

You can also view the example on JSFIDDLE.

Answer №4

Utilize $index alongside $parent.$index to access child and parent indexes.

 <div ng-repeat="segment in segments">
      <div ng-repeat="movement in movements">
        <button ng-click="clickedSegmentAndMovement($parent.$index,$index)">
      </div>
    </div>

    $scope.clickedSegmentAndMovement = function(segmentIndex,movementIndex) {
      console.log("Segment Index: " + segmentIndex + "And Movement Index: " + movementIndex);
    };

Answer №5

Give it a shot

<div ng-init="parentIndex = $index"> </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

"Maximize Interaction: Integrate interact.js with your Vue components

Previously, I had set up my project with two boards for dragging and dropping cards. However, I am now interested in experimenting with interact.js because it seems like a reliable library that is well-maintained. Since I am using vue for this project, I a ...

Accessing XML content within a web browser

I am facing an issue with parsing a string in JavaScript. var output = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><abc><xyz><xyzResponse><URL>http%3A%2F%2Flocalhost%3A8080%2Fnet%2Fxyz.do%3Fpartner%3Ddummy%26 ...

The onProgress event of THREE.JS Loader will only be triggered once the loading process has been successfully completed

Despite following numerous tutorials, I am struggling to receive regular updates on the loading progress when loading a model in order to create a loading icon. No matter what method I try, the onProgress function only triggers once, and that's after ...

Tips for retrieving return values from AJAX URL content

As I am writing some code to send data from one page to another through the ajax URL, I encountered an issue where the retrieved values on the previous page are showing as null. The first page code looks like this: <script> function myFunction() { ...

Tips for adding a hidden element along with an inline-block display styling

I am faced with a dilemma in my coding project. I want a div to have both inline-block and display none properties simultaneously, but it seems like I can only choose one option. This is a snippet of my HTML code: .like_user_wrapper{ margin-top:20px; ...

javascript challenge with inheritance

I am encountering an issue with two objects where one inherits from the other. The parent object is sending an ajax request to send some contact email. However, when I use the child object to send the request, all data is empty for some reason. The ajax r ...

What is the best way to ensure uniform container sizes and properly align images within them?

Customize Image Sizes: Is there a way to set a standard container size and adjust image sizes properly without compromising clarity or aesthetics? The images vary in dimensions, so should they be standardized or is there another solution? Code snippet: ...

Exploring the various repetition options in Three.js

There are three wrapping modes available in three.js: THREE.RepeatWrapping THREE.ClampToEdgeWrapping THREE.MirroredRepeatWrapping Interestingly, in OpenGL, there are four modes to choose from. Take a look at this image for reference I am looking to imp ...

Tips for preventing curved links in a radial tree diagram created with d3

I am currently utilizing this code to generate a radial tree diagram for my data. However, I am looking to make a modification to eliminate curved links. My preference is for linear connections instead of curved ones as the curved links can make the visual ...

Getting the parameters of a path from the URL's breadcrumb in Vue.js

Currently utilizing Vue Attempting to include path parameters in breadcrumb URLs for my app's router. Looking to achieve something similar to the following: { path: 'pages/gestion/region/:reg', name: 'gestion-depa', ...

Display the value of the textbox in real time using PHP without the need for a submit button or

I am looking to dynamically update another textbox with the value entered in a text field using PHP. The user input should be displayed in real-time as they type, and also echo the amount selected above the text field. Value is: (text entered in the textbo ...

Click a button to dynamically create a div element with jQuery

Whenever I click the button to add an address, I want to dynamically create a new div structure using jQuery <div id="container"> <div class="address"> <div class="input-reg rb-item input-group"> <sp ...

Dealing with various HTTP response codes in AngularJS

Here is the code for my AngularJS controller and factory: angular.module('app').controller('userCtrl', function($scope, User) { $scope.users = []; User.getUsers().then(function(response) { $scope.users = response.data; ...

What is the best way to filter out and combine one array from two arrays in lodash based on their unique properties?

Lodash v 4.17.15 Consider the scenario where two arrays are involved: var users = [{ id: 12, name: Adam },{ id: 14, name: Bob },{ id: 16, name: Charlie },{ id: 18, name: David } ] var jobs = [ ...

Unable to locate the controller in AngularJS

I am facing an issue with my AngularJS application where I have 2 separate JS files for different modules in different directories. When I try to start my app, I receive an error message stating that the controller SubAppCtrl cannot be found. Can someone p ...

Promise of bluebirds when working with an array of functions

I am working with an array of functions that are stored in a JSON file: "functionArray" : ["task1()", "task2()", ... , "taskN()"] My objective is to call these tasks sequentially, ensuring that task2 function is only executed after task1 function complete ...

Changing a MySQL "where" clause into a Sequelizejs "where" clause

Struggling to translate the query "WHERE (CASE ... THEN ... ELSE ... END) > 0" into sequelize v3.33. Tried using sequelize.literal('...') without success. Although using "HAVING" is a potential solution, it's not ideal for performance wi ...

Creating a webpage that seamlessly scrolls and dynamically loads elements

Currently, I am working on a dynamic website that loads new elements as you scroll down the page. Here is an example of the HTML code: <div>some elements here</div> <div id="page2"></div> And this is the JavaScript code: var dis ...

Create a random number from a custom list with assigned weights

I have a unique challenge ahead of me as I tackle this task in both PHP and JavaScript. Within a range of 1 to 300-500 numbers (limit not finalized), I need to conduct a drawing where 10 random numbers are selected. The twist: I want certain numbers to h ...

modifying the identification value in HTML and then reverting it

Although this may seem like messy code, I'm really in need of assistance with a problem that has stumped me. Currently, I am working on an E-shop project where I have modals for displaying products. Within these modals, there is a button that allows u ...