Assigning index values to child rows in AngularJS: a step by step guide

One of my requirements involves assigning index values to child rows. The structure includes group rows with child rows underneath. Currently, I am using ng-repeat along with $index for the children as shown below:

HTML code:

<table ng-repeat="node in data">
<tr> <td> {{node.groupName}} </td> </tr>
<tbody ng-model="node.nodes">
<tr  ng-repeat="node in node.nodes"> <td> {{$index}} </td> </tr>
</table>

However, the output is different from what I want:

https://i.stack.imgur.com/uQGyJ.png

I aim to achieve a display similar to this:

https://i.stack.imgur.com/ZNYAw.png

Being new to AngularJS, I am unsure about how to accomplish this layout. Any guidance on how I can achieve the desired result would be greatly appreciated.

Answer №1

Upon reviewing your query, it seems like you are seeking something along these lines:

<table ng-repeat="group in data">
  <thead> 
    <th> {{group.name}} </th> 
  </thead>
  <tbody ng-repeat="item in group.items"> 
    <tr> 
      <td>{{getIndex($parent.$index - 1, $index)}} | {{item}} </td> 
    </tr> 
  </tbody>
</table>

    $scope.data = [
      {name: 'Group1', items: ['a','b']},           
      {name: 'Group2', items: [1,2,3]},
      {name: 'Group3', items: ['x', 'xx', 'xxx', 'xxxx']}
    ];

    $scope.getIndex = function(previousGroupIndex, currentItemIndex){
      if(previousGroupIndex >= 0){
        var previousGroupLength = getPreviousItemsLength(previousGroupIndex);
        return previousGroupLength + currentItemIndex;
      }
      return currentItemIndex;
    };

    function getPreviousItemsLength(currentIndex){
      var length = 0;
      for (var i = 0; i <= currentIndex; i++){
        length += $scope.data[i].items.length;
      }
      return length;

      // or even better to use Array.prototype.reduce() for that purpose
      // it would be shorter and beautiful
      // return $scope.data.reduce(function(previousValue, currentGroup, index){
      //    return index <= previousGroupIndex ? previousValue + currentGroup.items.length : previousValue;
      // }, 0);
    }

To achieve this structure, you will need to manipulate $parent.$index property while utilizing some mathematical operations.

The final result will resemble the image linked below:

https://i.stack.imgur.com/TD10U.jpg

For a live demonstration, refer to this JSFiddle example.

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 REST API is producing a "Network connection Failure" error in Chrome, while it is functioning correctly in Firefox

My REST API has been experiencing inconsistent performance - sometimes it fails and other times it works fine in Chrome, but consistently works in Firefox. There have been instances where old data is returned when calling the API, even though CORS is prope ...

Monitor Socket IO for client disconnection events

I am facing an issue where I need to identify when a user loses connection to the socket. It seems that socket.on("disconnect") is not triggering when I simply close my laptop, leading to the ajax call not executing to update the database and mark the us ...

Transitioning from a traditional CURL method to utilizing AJAX and XMLHttp

I'm currently facing a challenge converting the curl code from an API named TextRazor to AJAX XMLHttp due to limitations on the platform I am working with. Despite trying various solutions shared by the community, I have been unsuccessful in retrievin ...

How can I ensure my AngularJS Controller variable is accessible across all page contexts?

Working with AngularJS, I have a view controller where I initialize a variable called recipesData. Here is the code for the controller: (function() { 'use strict'; angular .module('myApp') .controller('Coo ...

AngularJS: Issue with JQuery Slider not Updating Scope Value

I am currently working on a project using AngularJS and I have integrated a jQuery slider into it. However, I am facing an issue where I need to change the value of a select box which is defined in a $scope array, but the functionality is not working as ex ...

Utilizing properties to transfer a reference object to a nested component

Is it safe to do the following in React: function Parent() { const myRef = useRef([1, 2, 3]); console.log("parent: " + myRef.current); return <Child myList={myRef.current} />; } function Child({ myList }) { const [currInt, setCurrInt] = useS ...

How to handle an unexpected keyword 'true' error when using the `useState` hook in React?

Trying to set the open prop of the MUIDrawer component to true on user click is causing an error stating "Unexpected keyword 'true'" import React, { useState } from "react"; import { withRouter } from "react-router-dom"; impo ...

What is the best way to break out of a function halfway through?

What are your thoughts on using nested if statements? $scope.addToCart = function () { if (flagA) { if (flagB) { if (flagC) { alert('nononono!'); return; } } } e ...

How can I include an md-icon in an md-button within node-red-dashboard?

As a beginner in node-red, dashboard, AngularJS, and the pre-installed icons in the node-red dashboard, I humbly ask for guidance. My goal is to create custom buttons with icons using the dashboard template node. Based on the example provided in the inform ...

Pass on the error to the callback in Node.js

Here is the code snippet in question: User.findById(id, function(err, user) { //blah blah }); The findById method can be found within the User module. Here's a glimpse at its implementation: exports.findById = function(id,callback) { connec ...

Using a checkbox to enlarge a table

<script type='text/javascript' src='http://code.jquery.com/jquery-1.4.2.js'></script> <script type='text/javascript'> $(window).load(function () { $('.varx').click(function () { ...

Have you ever wondered why a listener on the 'data' event interprets two separate requests as one, unless a timeout is added?

It seems that there is a tricky issue with node where it combines 2 different requests into one unless a timeout is added. In the code snippet below, if we write 'one' and 'two' to the server and push the result to an array, node interp ...

When it comes to using the jQuery get method, it may not always yield the desired results. However, utilizing it within a form context,

Upon loading my website, users are directed to a file named index.jsp. My goal is to send a get request to one of my servlets when this page loads. The initial URL is: localhost:8080/Test/ The servlet should perform an action when the URL changes to: loc ...

Why is passing data:{} to a route essential for achieving the desired outcome?

Check out the Angular Material Documentation Site passing {} to the Homepage route: {path: '', component: HomePage, pathMatch: 'full', data: {}} I'm interested in knowing the significance of data: {}. Recent Discovery Closer ex ...

Tips for swapping out a div tag with another div tag in the same spot without needing to redirect to a different page by utilizing bootstrap

Currently, I am developing a JSP project that utilizes Bootstrap for the frontend. I have come across a question regarding HTML design. Is there a way to replace one div tag with another div on the same page without navigating to a new URL using Bootstrap ...

JavaScript updates the cursor after the completion of the JS function

Here is some code that I have been working with: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> </head> <body style="background-color:yellow;width ...

Difficulty in comparing passwords using bcrypt encryption method

As a beginner in express js, I have successfully implemented the register functionality in my app. However, I am facing an issue with the login process. I am trying to compare the password stored in the database with the one provided by the user using bcry ...

Preventing horizontal swiping while vertically scrolling on mobile devices

How can I prevent horizontal swipe functionality from interfering with vertical scrolling on a webpage? I have successfully blocked vertical scrolling but need help finding a solution for preventing horizontal swiping. Has anyone else encountered this issu ...

Node app experiencing issues with passport authentication request route only in production mode

Currently, I am facing an issue with my MERN app that includes passport for authentication flow. It runs smoothly in development mode but encounters major problems in production mode that I am struggling to resolve. The bug seems elusive and I can't p ...

Uh-oh! An unexpected type error occurred. It seems that the property 'paginator' cannot be set

I am developing a responsive table using Angular Material. To guide me, I found this helpful example here. Here is the progress I have made so far: HTML <mat-form-field> <input matInput (keyup)="applyFilter($event.target.value)" placeholder ...