Tips for utilizing ng-repeat with standard JSON data structures

I have a JSON structure like this:

 [{
  Entry: [{
    ID:123,
    Name: 'XYZ',
    Address: '600, PA'
  }, 
  {
    ID:123,
    Name: 'ABC',
    Address: '700, PA'
  },
{
    ID:321,
    Name: 'RRR',
    Address: '800, PA'
  },
{
    ID:321,
    Name: 'FFF',
    Address: '900, PA'
  }]
}]

I need to display the data in an HTML table as follows:

(Heading1)----------123----------

Row1- Name: XYZ Address: 600, PA

Row2- Name: ABC Address: 700, PA

(Heading2)----------321----------

Row1- Name: FFF Address: 800, PA

Row2- Name: RRR Address: 900, PA

I attempted using custom filters but was unable to implement ng-repeat. Is there an AngularJS method to achieve this? Thank you.

Answer №1

Utilizing Angular, I successfully parsed the JSON data to generate the desired output. Initially, I focused on organizing the JSON data in a structured format for easier traversal within the DOM. While there may be alternative methods, I believe this approach will prove beneficial. Below is my implementation:

The angular component:

angular.module("main", []).controller("MyCtrl", function($scope) {
var dataSrc = [
     {
       ID:123,
       Name: 'XYZ',
       Addredd: '600, PA'
     },
     {
       ID:123,
       Name: 'ABC',
       Addredd: '700, PA'
     },
     {
       ID:321,
       Name: 'FFF',
       Addredd: '800, PA'
     },
     {
       ID:321,
       Name: 'RRR',
       Addredd: '900, PA'
     },
     {
       ID:322,
       Name: 'RRR',
       Addredd: '900, PA'
     }
  ];

   var newDataSrc = new Array();
   var tempDataSrc = new Array();
   var idList     = new Array();
   for(i in dataSrc){
      var item = dataSrc[i];
      if(idList.indexOf(item.ID) !== -1){
        tempDataSrc[item.ID].push({'Name' : item.Name, 'Addredd': item.Addredd});
      }
      else{
        idList.push(item.ID);
        tempDataSrc.push(item.ID);
        tempDataSrc[item.ID] = new Array();
        tempDataSrc[item.ID].push({'Name' : item.Name, 'Addredd': item.Addredd});
      }
   }

   for(k in idList){
      var eachId = idList[k];
      var dataItem= [{'id' : eachId, 'data' : tempDataSrc[eachId]}];
      newDataSrc.push(dataItem);
   }

   $scope.items = newDataSrc;
});

The DOM section

<div ng-app="main">
   <div ng-controller="MyCtrl">
   <table>
     <tbody>
       <tr ng:repeat="item in items track by $index" ng-if="item != null">
         <td>
         (Heading) --------------{{item[0].id}}------------
          <div ng:repeat="info in item[0].data track by $index">
            Row{{$index + 1}} - Name: {{info.Name}} Addredd: {{info.Addredd}}
          </div>
         </td>
       </tr>
     </tbody>
   </table>
   </div>
</div>

Result

(Heading) --------------123------------
Row1 - Name: XYZ Addredd: 600, PA
Row2 - Name: ABC Addredd: 700, PA
(Heading) --------------321------------
Row1 - Name: FFF Addredd: 800, PA
Row2 - Name: RRR Addredd: 900, PA
(Heading) --------------322------------
Row1 - Name: RRR Addredd: 900, PA

Answer №2

Agreeing with Claies, I also believe that restructuring your data is crucial for aligning it with your desired view. Your ideal data structure should resemble the following:

[{
  ID:123,
  Entry: [{
    Name: 'XYZ',
    Address: '600, PA'
  }, 
  {
    Name: 'ABC',
    Address: '700, PA'
  }]
},
{
  ID:321,
  Entry: [{
    Name: 'FFF',
    Address: '800, PA'
  }, 
  {
    Name: 'RRR',
    Address: '900, PA'
  }]
}]

By organizing your data in this format, you will be able to utilize a nested ng-repeat to achieve your desired outcome.

Answer №3

Take a look at the JSON data provided


{
    "456": [
        {
            "Label": "EFG",
            "Location": "123, NY"
        },
        {
             "Label": "HIJ",
             "Location": "456, LA"
        }
    ],
    "789": [
         {
              "Label": "KLM",
              "Location": "789, SF"
         }
     ]
}

}

Implement ng-repeat for both header and inner loop.

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

Implementing icon display upon click in a Meteor application

Currently, I am in the process of developing an application using meteor and within one of the templates, I have the following code snippet. <h3> <b> <a class="viewed" href="/jobdetails/{{_id}}">{{title}}</a> </b> ...

What is the best way to update the values of an array of object properties using an input form in JavaScript?

I'm currently learning node.js, express.js, and handlebars I am working on creating two forms for a blog/news page: an add form and an edit form. /addproject: app.get('/addproject', function(req, res) { res.render('addprojec ...

What is the best way to customize column width in AG-Grid?

I am looking for a way to dynamically set column width in my table. I have provided a stackblitz example which demonstrates that when changing the screen size, only the table border adjusts, but not the column widths. Is there a way to also change the col ...

Solution: Replace occurrences of 'window' with 'global' for improved

Currently experimenting with a component on runkit.com. The platform is advising me to make a change based on the image provided... Solution: Use global instead of window. Since RunKit operates in a node environment, browser-specific features like win ...

What is the main object used in a module in Node.js for global execution?

Node.js operates on the concept of local scope for each module, meaning variables defined within a module do not automatically become global unless explicitly exported. One question that arises is where a variable declared in a module file belongs in term ...

The Full Screen Button on Google Maps isn't functioning properly in a third-party mapping application

Below you will see the '+' icon which is also supposed to function as the full screen button. https://i.stack.imgur.com/IMvHa.png However, when clicked on, it does not expand to full screen as intended. I have attempted using some basic jQuery ...

reasons why the keypress event may not be triggered

Hello there, I am trying to create a function that simulates pressing the 'tab' key. The function is supposed to restrict input within specific ranges and return the cursor to another range once the limit is reached. Additionally, if a user input ...

Is it possible to have the soft keyboard automatically appear when the page loads?

On an HTML5 website, I have an input element and I want the soft keyboard to automatically appear and focus on that input element. I attempted to use the 'autofocus' attribute on the 'input' element, but this only focused on the element ...

ERROR TRACKER: Unable to locate file "CL.exe". File not found in system

I am attempting to run the following command in a Node.js project on my Windows 8 machine: npm install [email protected] However, I am encountering an error that I am not sure how to resolve. TRACKER : error TRK0005: Failed to locate: "CL.exe". ...

Issue with Inline JavaScript in `href` tag not functioning correctly in Firefox

I am encountering an issue with this inline JavaScript not working in Firefox. I need to figure out how to make it function correctly in Firefox. <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <style> ...

"What could be the reason for web3.eth.getAccounts() method returning an empty array when used with console.log

Upon executing web3.eth.getAccounts().then(console.log);, I encountered an empty array and also received a warning stating ./node_modules/web3-eth-accounts/src/scrypt.js Critical dependency: the request of a dependency is an expression. The project began w ...

Encountering issues in parsing JSON for PhoneGap Application

I've been struggling with parsing JSON data for a unique PhoneGap application that is dynamically generated by a localStorage variable. The PHP script is functioning properly, but the JavaScript code seems to be encountering issues when trying to pars ...

Unexpected issue encountered for identifiers beginning with a numerical digit

Is it possible to select an element from a page with an id that begins with a number? $('#3|assets_main|ast_module|start-iso-date') Upon attempting to do so, the following error occurs: Uncaught Error: Syntax error, unrecognized expression: ...

Updating an array in JavaScript with a dynamically generated key name while working in the ReactJS framework

I have multiple dropdown menus, and when I select an option from any of them, I want to store the selected value in the component state. The onChange function that I call looks like this: function handleSelect(event) { console.log(event.target.value); ...

Can the second function be modified to incorporate the first one's syntax?

export const composeValidators = (...validators) => value => validators.reduce((error, validator) => error || validator(value), undefined); export const composeAccreditionValidators = (...validators) => value => validators.reduce((error, va ...

What could be causing my Angular Ngrx app's state not to render properly on the application?

Is there a way to automatically render the state when the app loads without having to click a button? I am currently facing an issue where the state is empty until I manually trigger the click function by pressing a button. I have tried using this.store.se ...

Sending HTML content to viewChild in Angular 5

I'm struggling to figure out how to pass HTML to a ViewChild in order for it to be added to its own component's HTML. I've been searching for a solution with no luck so far. As a newcomer to Angular, many of the explanations I find online ar ...

Issue with kendo grid not properly saving recently added data

Unexpected Grid Behavior: Adding a new record Pressing the update button in the grid for the newly added row Cancelling before saving After completing the above actions, the newly added row disappears. View js fiddle example <!DOCTYPE html> <h ...

What could be causing the Material-UI Appbar onLeftIconButtonTouchTap function to malfunction?

I am currently learning React-Redux and Material-UI. I'm working on creating a Sample App, but I'm facing some difficulties. I need help in improving my code. Specifically, I am trying to make the Drawer open when the Material-UI AppBar's on ...

What is the best way to send a string without using quotation marks as a parameter in a function?

If I have an API that takes the query as http://localhost:8000/api/v1/rental/?place__startswith=kathmandu, how can I implement a generic search in ReactJS? What I attempted to do is pass the default parameter as search(query=kathmandu) so that the result ...