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

Tips for alternating the color of <li> or <tr> elements consecutively

Looking to alternate the background color of li or tr elements consecutively. Please note: A static class will not work as I need to call this in a while loop. The desired output should look like: <li>line1</li> //white background <li> ...

Learn the steps to resolve pagination issues in React. When the first page loads, ensure all data is displayed properly. Click

Here is an excerpt from my code snippet: const Inventory = () => { const [products, setProducts] = useState([]); const [pageCount,setPageCount] = useState(0); //console.log(pageCount); const [page,setPage] = useState(0); const navigate = useNa ...

How to incorporate Mixin in your Nuxt template

I'm having trouble utilizing the mixin function in my template. Although Vue documentation states that mixins and components are merged, I am unable to call the function. getImage is not a function Mixin export default { data() { return { ...

Having trouble importing OrbitControls in three.js with an error?

I'm currently working on localhost and I've encountered an issue while trying to import "orbitcontrols()" which is not functioning properly and displaying an error. Here is the error message main.js:1 Uncaught SyntaxError: Cannot use import stat ...

Inheritance best practices for node.js applications

In C#, the concept of inheritance can be easily demonstrated through classes like Animal and Dog. class Animal { string name; public Animal() { } } class Dog : Animal { public Dog() : base() { this.name = "Dog"; } } When working ...

WebStorm not recognizing NodeJS Core Modules in External Libraries

As a newcomer to NodeJS and WebStorm, I am currently diving into a tutorial on creating an Express app. In the tutorial, the instructor always gets prompted with "Configure NodeJS Core Module Sources" including the URL nodeJS.org when creating a new NodeJ ...

Identify the transition of the parent element containing the <iframe> from a hidden state to a

Is there a way to identify when an iframe is shown after being hidden? HTML : <div style="display:none"> <iframe></iframe> </div> When the <div> is displayed using jQuery with $('div').show();, how can I determi ...

AngularJS and Gulp: Enhancing Static Assets with Revisioning

I have implemented the gulp-rev module to re-vision static assets in my source files. It generates new file names for CSS, JS, and HTML files by appending a hash code to it. Before : app.js After : app-2cba45c.js The issue I am facing is that in my An ...

Navigating through JavaScript links in Selenium (Scrapy) and returning to the initial page: A step-by-step guide

Having some difficulties with pages that have javascript links embedded in them. This issue arises when the page contains a list of cities with javascript in their links. Each link needs to be navigated individually, scraping information and then returning ...

Utilizing the JSON.parse method in JavaScript in conjunction with an Ajax request while incorporating the escape character "\n" for new line functionality

https://jsbin.com/zuhatujoqo/1/edit?js,console Edit: json file has this line: {"pd":"ciao \\n ste"} I need to retrieve a valid JSON file through an ajax call. Then parse the result using JSON.parse. I'm confused about the behavior of t ...

Ways to implement functional component in ReactJs

I am currently working with Reactjs and utilizing the Nextjs framework. In my project, I am attempting to retrieve data from a database using Nextjs. However, I am encountering an error that states "TypeError: Cannot read property 'id' of undefin ...

Bootstrap does not show submenus on its navigation menus

I am currently designing a menu with Bootstrap, but for some reason, the submenu items are not showing up. https://i.stack.imgur.com/qZqyf.png After carefully reviewing the HTML code multiple times, I am unable to identify any issues. I am now questionin ...

How can I programmatically trigger a change event for a dropdown in Vue.js?

I am looking to trigger a dropdown change event within a Vue.js method. <select id="idDropdown" v-model="Result.Value" v-on:change.prevent="changeSelection($event, 'somevalue')"> How can I call the above `cha ...

Use Javascript to conceal a div element if there are no links present

I am working on a website using ModX CMS and I am attempting to hide or remove a div element when it does not contain any anchor tags. How can I achieve this? I have already attempted the following code without success: jQuery(function($) { if ($(".pages ...

Using both Ajax and a standard submit can be applied to a single form in jQuery

I need to implement a confirm step on one of my pages. Here's what I want to achieve: When the user clicks 'submit', an AJAX request is triggered, which performs the necessary action and then displays a confirmation dialog If the user ...

Can we ensure that the function is called when a node is located?

Presently, I am executing the following code but it is causing the call stack to slow down; how can I optimize this using either an async await or more advanced promise functions? I have a dynamic node that is added to the DOM at different times dependin ...

Retrieving selections from a group of checkboxes and managing their addition or removal in an array

Currently, I am in the process of creating a form that includes a group of checkboxes. My goal is to be able to capture the value of a specific checkbox when it is clicked and add it to an Array using the useState hook. If the checkbox is unchecked, I wan ...

Having trouble with ng-repeat in AngularJS after including Angular 17 web components to index.html?

<select ng-if="!isOtherRemarkSelected" class="form-control m-1" ng-model="selectedRemark.value" ng-change="handleRemarks()"> <option value="">Select Remarks</option> <op ...

Ionic utilized the $http service and was unexpectedly triggered two times

$scope.login = function(email,password){ $http({ method: 'POST', url: 'http://example.com/login', headers: { 'owner': $rootScope.secret }, data: {email:email, password:password } }).then(function successCallback(response) { co ...

Combining two functions in AngularJS

I have two factories for readability, along with one controller. I am unsure if it is feasible, but I am interested in combining the results of the two factories into one variable. code vm.result = []; vm.validate = validate; function validate(password1, ...