Showcasing Information Using AngularJS from a Json Array

My goal is to present data from a JSON array in a table using the code below. However, all the data is currently being shown in one row instead of each record appearing on separate rows with alternating colors - grey for even rows and white for odd rows. I suspect there is an error in my implementation but I can't seem to pinpoint it.

CSS Style:

table,td  {
    border: none;
    border-collapse: collapse;
    padding: 5px;
    width:1047px;
    height: 64px;
    left:16px;
    position:relative;
}
table tr:nth-child(odd) {
    background-color: #f1f1f1;
}
table tr:nth-child(even) {
    background-color: #ffffff;
}

My View (This snippet is displayed within index.html):

      <h1 id="title">Shuttle Schedule</h1>
        <table width="100%" cellpadding="4" cellspacing="25" style="margin-top:-118px">
            <thead  align="center">
                <th ng-repeat="row in module.csvInput">{{row.label}}</th>
                <th ng-repeat="row in module.csvInput">{{row.label}}</th>

            </thead>
            <tr align="center" >
                <td ng-repeat="row in module.csvInput" >
                    <div ng-repeat="(id, time) in row.times" ng-if="id <= 8">
                    {{time}}
                    </div>

                </td>
                <td ng-repeat="row in module.csvInput">
                    <div ng-repeat="(id, time) in row.times" ng-if="id > 8">
                        {{time}}
                    </div>

                </td>
            </tr>
        </table>
        <h3 class="noservice">No Service 1:20pm to 2:00pm<br> Driver can make additional runs beyond this schedule if needed.<br>
            D1 is 8910 Ridgeline Blvd. D4 is 8744 Lucent Blvd.</h3>
    </div>

Snippet of My JSON Data:

{
  "modules": [


    {
      "title": "Shuttle Schedule",
      "feature": "shuttle",
      "order": 4,
      "csvInput": [
        {
          "label": "D1 PickUp",
          "times": [
            "8:00 AM",
            "8:30 AM",
            "9:00 AM",
            "9:30 AM",
            "10:00 AM",
            "10:30 AM",
            "11:00 AM",
            "11:30 AM",
            "12:00 PM",
            "12:30 PM",
            "1:30 PM"
          ]
        },
        {
        "label": "D4 PickUp",
        "times": [
          "7:50 AM",
          "8:20 AM",
          "8:50 AM",
          "9:20 AM",
          "9:50 AM",
          "10:20 AM",
          "10:50 AM",
          "11:20 AM",
          "11:50 AM",
          "12:20 PM",
          "12:50 PM",
          "1:10 PM"
        ]
      }
      ],
      "filter": null,
      "icon": "media/shuttle.svg"
    }
  ],
  "settings": {
    "buildings": 2,
    "floor": 4,
    "timeout": "120 (in seconds)",
    "cssOverride": "custom.css",
    "kiosk_coords": "200,200"
  }
}

Current Output: https://i.stack.imgur.com/7YZt1.jpg

Desired Presentation Style: https://i.stack.imgur.com/OcxCS.jpg

Answer №1

Make sure to apply the ng-repeat directive on the tr tag instead of the td tag initially. Your code should look something like this:

<table> <tr ng-repeat="entity in list"><td>{{entity.lable}}</td> 
<td ng-repeat="time in entity.times">{{time}}</td></tr></table>

UPDATE: If you want your data to be displayed in HTML as follows: entity.label : entity.time entity.label : entity.time ...

Then you might need to adjust your code as shown below:

<table> <div ng-repeat="entity in list"><tr ng-repeat="time in entity.times><td ng-class-odd="'grey'" ng-class-even="'white'">{{entity.lable}}</td> 
<td ng-class-odd="'grey'" ng-class-even="'white'">{{time}}</td></tr></div></table>

Answer №2

To present the data in a desired format, you must first unroll the data.

$scope.module = data.modules[0];
var csvInput = $scope.module.csvInput;
$scope.headers = csvInput.map(x => x.label );
var rows = csvInput.map(x => x.times.slice(0, 8)).concat(csvInput.map(x => x.times.slice(8)));
var n = Math.max.apply(null, rows.map(x => x.length));
$scope.rows = [];
for ( i = 0; i < n; i++ ) {
  $scope.rows[i] = rows.map(x => x[i]);
}

Once the data is prepared, it can be displayed using the following code:

<table width="100%" cellpadding="4" cellspacing="25" style="margin-top:-118px">
  <thead align="center">
    <th ng-repeat="row in headers">{{row}}</th>
    <th ng-repeat="row in headers">{{row}}</th>
  </thead>
  <tbody>
    <tr ng-repeat="row in rows">
      <td ng-repeat="col in row track by $index">{{col}}</td>
    </tr>
  </tbody>
</table>

A demo of this code can be seen at http://jsfiddle.net/r0005a1t/

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

Loading Collada files with a progress callback function can help track the

Is there a proper way to incorporate a loading bar while using the ColladaLoader? The code indicates that the loader requires three parameters, with one being a progressCallback. progressCallback( { total: length, loaded: request.responseText.length } ); ...

The sticky HTML table header feature is functional, however, the header's border disappears while scrolling

Utilizing the react-bootstrap-table2 library in my React project, I added custom CSS to create a sticky top row effect: .table-container { overflow-y: auto; max-height: 500px; } .react-bootstrap-table th { position: sticky; top: -1px; background- ...

Getting information in JSON format

Within my controller class, I have the following method: import javax.json.Json; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.c ...

Utilizing Javascript to implement a tooltip feature for dynamically inserted text

I recently incorporated a brief jQuery tooltip plugin into my site. It consists of approximately ten lines of code and works smoothly, as demonstrated in this demo. However, I encountered an issue when attempting to add new text that should also trigger t ...

Decoding JSON using JavaScript

I am dealing with a webservice that uses RestEasy to return a JSON object with a List element. When I try to parse the results in a JavaScript loop, everything works fine if there are two or more elements in the List. However, if there is only one element, ...

Efficiently utilizing CSS classes

My dilemma involves styling a textfield in two different locations on my website, each with its own parent element. The second location requires an additional margin-top that the first does not. What is a clever way to adjust the original margin-top withou ...

Something is seriously wrong with the datetime in fullcalendar JavaScript

I've been diving into a tutorial for creating a calendar scheduler in asp.net MVC5 from this link. One issue I'm facing is the datetime being passed and stored as the min value in the database (1/1/0001 12:00:00 AM), almost like it's null b ...

"Is there a way to convert a collection of lists into JSON format while

Here is a collection of lists including names, scores, and other data: [['Edan Daniele', '12.61', '5.00', '9.22', '1.50', '60.39', '16.43', '21.60', '2.60', '35 ...

What is the best way to automatically insert data into a database at regular intervals, while ensuring that users are unable to manipulate the timing through inspect

Is there a secure way to insert 1 point into the database every x seconds without allowing users to manipulate the interval time through inspect element? var time = 1; var interval = setInterval(function() { if (time != time + 1) { ...

Creating a custom dialog box using JavaScript

How can I create a customized dialog box in the center without displaying "the host name says..." using CSS? function myFunction() { alert("Record Save"); } Thank you in advance! ...

Harness the power of React Material-UI with pure javascript styling

I am currently attempting to implement Material-UI in pure javascript without the use of babel, modules, jsx, or similar tools. <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8 ...

Convert the existing JavaScript code to TypeScript in order to resolve the implicit error

I'm currently working on my initial React project using Typescript, but I've hit a snag with the code snippet below. An error message is popping up - Parameter 'name' implicitly has an 'any' type.ts(7006) Here is the complet ...

My CSS seems to be causing an issue and preventing the function from running correctly. Now I just need to

I'm currently working on a project and following a tutorial to help me create a navigation bar. The tutorial I am using can be found here: https://www.youtube.com/watch?v=gXkqy0b4M5g. So far, I have only reached the 22:05 mark in the video. I have su ...

Extend and retract within a row of a table

I need help with modifying a dynamically generated table to meet specific requirements. The table currently looks like this. The task involves hiding all columns related to Category B, eliminating duplicate rows for Category A, and displaying entries from ...

Modifying the color of drawings on a Javascript canvas

I am currently working on developing a drawing board using HTML and JavaScript (Node.js on the server side). One challenge I'm facing is implementing a color picker that allows users to change the paint color dynamically. While I could hard code the c ...

How to Transform JSON Element into a JavaScript Array in AngularJS?

Implementing AngularJS to fetch values in JSON format using $resource call. The model element I require is a Javascript array structured as: [ [1328983200000, 40], [1328983200000, 33], [1328983200000, 25], [1328983200000, 54], [1328983200000, 26], [1328 ...

Tips for generating an auto-incremented ID column in jQuery tables through the render method

My jQuery Datatable setup looks like this let purchasedProductTbl = $('#grdPurchasedProduct').DataTable({ filter: false, paging: false, lengthChange: false, searching: false, ordering ...

Using JavaScript to eliminate brackets

When a map is clicked, I have a function that retrieves GPS coordinates. However, the result is currently displayed in brackets (). It is necessary to eliminate the brackets. function onClickCallback(event){ var str = event.latLng var Gpps = str / ...

Creating a PHP JSON response that incorporates an HTML layout is a dynamic

I'm having some trouble with a certain issue: I am attempting to develop a jQuery/AJAX/PHP live search bar. Although I am successfully calling search.php, the response displayed in the console always includes the contents of my master.php file (which ...

Strategies for creating smooth transitions for elements using CSS transformations

Is there a way to smoothly fade in edits to elements in CSS when hovered over? I am looking to change the border from solid to dotted, but want the transition to be gradual. How can this be achieved? UPDATE: To provide more context, here is the current c ...