Tips for utilizing the ng-repeat scope within a nested ng-repeat

I currently have an array of objects structured as follows:

expMonthByCat: 
    {Food: [some values],
     Clothing: [some values]
    }

In conjunction with this data, there exists a table formatted in the following manner:

<tr data-ng-repeat="category in labels">
    <th scope="row">{{category}}</th>
    <td data-ng-repeat="expCat in expMonthByCat">{{expCat}}</td>
</tr>

An issue arises when trying to pass the variable category within the context of

<td data-ng-repeat="expCat in expMonthByCat">
. This is crucial due to the fact that category contains keys such as Food and Clothing, among others, present inside expMonthByCat.

I've attempted solutions such as:

<td data-ng-repeat="expCat in expMonthByCat.category">
and
<td data-ng-repeat="expCat in expMonthByCat">{{expCat.category}}</td>
, however, these attempts have been unsuccessful.

If anyone could provide guidance or assistance, it would be greatly appreciated. Thank you!

UPDATE

Upon utilizing

<td data-ng-repeat="expCat in expMonthByCat track by $index">
, the resulting output can be observed here: Image

In contrast, employing

<td data-ng-repeat="expCat in expMonthByCat.Food track by $index">{{expCat}}</td>
yields the depicted outcome here: Image

How can I ensure that the table displays its respective values accurately?

Below is a snippet of my JavaScript code for reference:

$scope.expMonthByCat = {};
for (z = 0; z < $scope.labels.length; z++) {
    $scope.expMonthByCat[$scope.labels[z]] = new Array(12);
    for (x = 0; x < 12; x++) {
         $scope.expMonthByCat[$scope.labels[z]][x] = 0;
    }
}

for (x = 0; x < 12; x++){
    for (i = 0; i < response.data[2].length; i++) {
        $scope.labels.forEach(function (k) {
            if(response.data[2][i].category == k){
                if (response.data[2][i].expMonth == x + 1 && response.data[2][i].expYear == currentYear){
                    var expByCat = response.data[2][i].expAmount;
                    $scope.expMonthByCat[k][x] = parseFloat(Number(expByCat).toFixed(2));
                }
            }
        });
    }
}

Answer №1

Here is the solution you're looking for:

<tr data-ng-repeat="category in labels">
    <th scope="row">{{category}}</th>
    <td data-ng-repeat="categoryExp in expMonthByCat[category]">{{categoryExp}}</td>
</tr>

Take a look at the live demonstration: jsfiddle

Answer №2

To effectively display all the headers in a table, you should utilize ng-repeat on a single table row first. Subsequently, employing nested ng-repeat will allow mapping of all the items corresponding to each category. You can extract the keys of the labels using

data-ng-repeat="(key,val) in labels"
.

angular.module('notesApp', [])
  .controller('MainCtrl', ['$scope', function($scope) {
    $scope.expMonthByCat = {
      Food: ['cake', 'burger'],
      Clothing: ['jeans', 't-shirt']
    }
    $scope.labels = Object.keys($scope.expMonthByCat);
  }]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<table border='1' ng-app="notesApp" ng-controller="MainCtrl">
  <tr>
    <th scope="row" data-ng-repeat="category in labels">{{category}}</th>
  </tr>
  <tr data-ng-repeat="(key,val) in labels">
    <td data-ng-repeat="expCat in expMonthByCat">{{expCat[key]}}</td>
  </tr>
</table>

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 boolean validation function appears to be malfunctioning in the NodeJS environment

I am currently working on developing the node js API and I am fetching data using a URL query. get_posts_default?pageId=ge4JqBn9F0srzHnVFHmh&asking_post=false&asking_responce=false&maxSort=-1&minSort=-1&limit=20 This function is respo ...

Retrieve telephone number prefix from Cookies using React

Being able to retrieve the ISO code of a country is possible using this method: import Cookies from 'js-cookie'; const iso = Cookies.get('CK_ISO_CODE'); console.log(iso); // -> 'us' I am curious if there is a method to obt ...

Timing issues during the sign-up process and triggering onAuthStateChanged() in a Vue application are leading to complications with user permissions

In my Vue application, I am looking to register users, create a user document, and then fill the state with relevant information by fetching data from a document in Firebase. I want to follow this sequence because if the tasks do not execute synchronously ...

jquery: scroll-triggered opacity effect

I am attempting to gradually increase the opacity of my div as the user scrolls, similar to this: $(document).ready(function() { $(document).scroll(function(e) { changeOpacity(); }); var element = $('#element'); var elem ...

Access account without providing all necessary identification documents

I'm currently facing an issue with my User Schema, as I initially defined 3 inputs for name, surname, and email. However, I now want to allow users to log in only with their email and password, without having to input their name and surname. How can I ...

Is it feasible to utilize the HTML5 video tag in conjunction with a JSON callback?

Curious about the possibility of a video page layout featuring a main screen and smaller clickable screens below it. When clicking on one of the smaller screens, the main screen would display the selected video, similar to YouTube. We have obtained data f ...

My code fails to recognize the top property when the window size is 1300px

Error at the Top Not Being Recognized: Hello, I am facing an issue where the top part of the webpage does not behave correctly when the window size is less than 1300px. The condition set for 100% top only applies after refreshing the page; otherwise, it d ...

Modifying Image on Tab Click using jQuery

In my current WordPress project, I am working on dynamically changing an image based on the tab that is clicked. I would like to use jQuery's fade effect to smoothly replace the image with a new one that is relative to the specific tab being clicked. ...

What is the best way to retrieve users.cache from all shards and consolidate them into a collection similar to the one returned by client.user.cache?

My discord bot originally used the following code: client.users.cache This would provide me with a Collection[Map] containing all the cached users. Recently, I implemented sharding and attempted to replicate this using: client.shard.fetchClientValues(&ap ...

Can Dropdown Items Be Generated Dynamically?

In the realm of React development, I find myself in need of a specific number of dropdown menus for a particular project. Each dropdown menu is expected to offer multiple options for selection. Typically, I would employ a straightforward map function to ha ...

Processing ajax requests in Rails 4 using HTML format

I'm currently in the process of setting up ajax functionality for my contact form and I am currently testing to ensure that the ajax call is being made. When checking my console, I noticed that it is still being processed as HTML and I cannot seem to ...

Unable to access the 'data' property because it is undefined in AngularJS, making it impossible to retrieve data from the template to the controller

I am new to angularjs and still learning its intricacies. Currently, I am facing an issue where I can't seem to find a simple solution. I hope someone can assist me with this. Here is the folder structure that I have created: Select ->SelectModu ...

What could be causing the tooltip to appear in the wrong position

It may seem like a trivial issue, but I am struggling to get my tooltips to display in the correct position. No matter what I try, they always appear off position. I have searched for solutions and attempted to rearrange the order of scripts, add new scri ...

Using jQuery to remove an iframe upon a click event

My goal is to remove an iframe whenever anything on the page is clicked. I tried using this code: $('*').on('click',function(){ $('iframe').remove(); }); However, I encountered a problem where the i ...

Utilizing an npm package within vscode with the .Vue framework: A step-by-step guide

After installing an npm package, I realized that it is written in JS while I am using the Vue framework. Even though Vue is based on JS, its syntax differs from traditional JS. How can I effectively integrate this package into my Vue project? I successful ...

When the span tag is inserted into a contenteditable element on iOS Safari, the cursor automatically shifts to the

One interesting feature allows users to click on a tag and have it added to a contenteditable div. This function works smoothly initially, but when toggling back and forth, the cursor unexpectedly jumps to the end of the div. When a user adds a variable f ...

Tips for enhancing the transition effect of animated gifs on a webpage using JavaScript

In my code, I have an interval set to run every seven seconds. Within this interval, there are two gifs that each last for seven seconds. My goal is to display one of the gifs in a div (referred to as "face") based on certain conditions - for example, if t ...

Steps for closing the menu by clicking on the link

My issue with the menu on the landing page is that it only closes when clicking the cross button. I want it to close when any link from the menu is clicked. I attempted to add code using querySelector, but it only worked for the home link and not the other ...

The property 'scrollHeight' is undefined and cannot be read

I've created a messaging system using javascript and php, but I'm facing an issue. When new messages are received or the chat log grows longer, it creates a scrollbar. The problem is that when a new message arrives, the user has to manually scrol ...

Data Malfunction Leads to Failure of Ajax POST Request in Client-Side Operation

I am facing an issue where my Ajax POST calls are failing when I attempt to assign complex JavaScript objects to the [data] key/value pair after using JSON.stringify() for serialization. Could anyone advise on what additional ajax call configuration is re ...