[javascript] Create Table from JSON Data with angularjs and ng-repeat

I have the following data as JSON:

{
  "Workout1": {
    "Name": "First",
    "Rounds": [
      {
        "Exercises": [
          {
            "Name": "Exercise1",
            "Repeat": 10
          },
          {
            "Name": "Exercise2",
            "Repeat": 10
          },
          {
            "Name": "Exercise3",
            "Repeat": 10
          }
        ]
      },
      {
        "Exercises": [
          {
            "Name": "Exercise1",
            "Repeat": 20
          },
          {
            "Name": "Exercise2",
            "Repeat": 20
          },
          {
            "Name": "Exercise3",
            "Repeat": 20
          }
        ]
      },
      {
        "Exercises": [
          {
            "Name": "Exercise1",
            "Repeat": 30
          },
          {
            "Name": "Exercise2",
            "Repeat": 30
          },
          {
            "Name": "Exercise3",
            "Repeat": 30
          }
        ]
      }
    ]
  }
}

and I want to display it as a html table with angularjs and ng-repeat. so that I get the following table:

<table class="table">
    <tr>
        <th>Round1</th>
        <th>Round2</th>
        <th>Round3</th>
    </tr>
    <tr>
        <td>10 Exercise1</td>
        <td>20 Exercise1</td>
        <td>30 Exercise1</td>
    </tr>
    <tr>
        <td>10 Exercise2</td>
        <td>20 Exercise2</td>
        <td>30 Exercise2</td>
    </tr>
    <tr>
        <td>10 Exercise3</td>
        <td>20 Exercise3</td>
        <td>30 Exercise3</td>
    </tr>
</table>

for table preview: http://jsfiddle.net/54pD8/

my problem that the html table is working row-based. I can iterate with ng-repeat through my Rounds and then through my excercises but for creating a table I need always the first of each exercises then the second of each exercises and so on.

Can someone help me with this problem?

ps. if you have an idea for better layout for this data in json, your suggestions are welcome, I'm new to json (and angularjs).

This question is related to javascript html json angularjs

The answer is


To create HTML table using JSON, we will use ngRepeat directive of AngularJS.

Example

HTML

<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<table border="1">
<tr ng-repeat="x in names">
<td>{{x.Name}}</td>
<td>{{x.City}}</td>
<td>{{x.Country}}</td></tr>
</table>
</div>
</body>
</html>

JavaScript

var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope) {
    $scope.names = [
      { "Name" : "Max Joe", "City" : "Lulea", "Country" : "Sweden" },
      { "Name" : "Manish", "City" : "Delhi", "Country" : "India" },
      { "Name" : "Koniglich", "City" : "Barcelona", "Country" : "Spain" },
      { "Name" : "Wolski", "City" : "Arhus", "Country" : "Denmark" }
    ];
});

In above example I have created table from json. I have taken reference from http://www.tutsway.com/create-html-table-using-json-in-angular-js.php


Easy way to use for create dynamic header and cell in normal table :

<table width="100%" class="table">
 <thead>
  <tr>
   <th ng-repeat="(header, value) in MyRecCollection[0]">{{header}}</th>
  </tr>
 </thead>
 <tbody>
  <tr ng-repeat="row in MyRecCollection | filter:searchText">
   <td ng-repeat="cell in row">{{cell}}</td>
  </tr>
 </tbody>
</table>

MyApp.controller('dataShow', function ($scope, $http) {
    //$scope.gridheader = ['Name','City','Country']
        $http.get('http://www.w3schools.com/website/Customers_MYSQL.php').success(function (data) {

                $scope.MyRecCollection = data;
        })

        });

JSON Data :

[{
    "Name": "Alfreds Futterkiste",
    "City": "Berlin",
    "Country": "Germany"
}, {
    "Name": "Berglunds snabbköp",
    "City": "Luleå",
    "Country": "Sweden"
}, {
    "Name": "Centro comercial Moctezuma",
    "City": "México D.F.",
    "Country": "Mexico"
}, {
    "Name": "Ernst Handel",
    "City": "Graz",
    "Country": "Austria"
}, {
    "Name": "FISSA Fabrica Inter. Salchichas S.A.",
    "City": "Madrid",
    "Country": "Spain"
}, {
    "Name": "Galería del gastrónomo",
    "City": "Barcelona",
    "Country": "Spain"
}, {
    "Name": "Island Trading",
    "City": "Cowes",
    "Country": "UK"
}, {
    "Name": "Königlich Essen",
    "City": "Brandenburg",
    "Country": "Germany"
}, {
    "Name": "Laughing Bacchus Wine Cellars",
    "City": "Vancouver",
    "Country": "Canada"
}, {
    "Name": "Magazzini Alimentari Riuniti",
    "City": "Bergamo",
    "Country": "Italy"
}, {
    "Name": "North/South",
    "City": "London",
    "Country": "UK"
}, {
    "Name": "Paris spécialités",
    "City": "Paris",
    "Country": "France"
}, {
    "Name": "Rattlesnake Canyon Grocery",
    "City": "Albuquerque",
    "Country": "USA"
}, {
    "Name": "Simons bistro",
    "City": "København",
    "Country": "Denmark"
}, {
    "Name": "The Big Cheese",
    "City": "Portland",
    "Country": "USA"
}, {
    "Name": "Vaffeljernet",
    "City": "Århus",
    "Country": "Denmark"
}, {
    "Name": "Wolski Zajazd",
    "City": "Warszawa",
    "Country": "Poland"
}]

You can use $http.get() method to fetch your JSON file. Then assign response data to a $scope object. In HTML to create table use ng-repeat for $scope object. ng-repeat will loop the rows in-side this loop you can bind data to columns dynamically.

I have checked your code and you have created static table

<table>
<tr>
<th>Name</th>
<th>Relationship</th>
</tr>
<tr ng-repeat="indivisual in members">
<td>{{ indivisual.Name }}</td>
<td>{{ indivisual.Relation }}</td>
</tr>
</table>

so better your can go to my code to create dynamic table as per data you column and row will be increase or decrease..


Angular 2 or 4:

There's no more ng-repeat, it's *ngFor now in recent Angular versions!

<table style="padding: 20px; width: 60%;">
    <tr>
      <th  align="left">id</th>
      <th  align="left">status</th>
      <th  align="left">name</th>
    </tr>
    <tr *ngFor="let item of myJSONArray">
      <td>{{item.id}}</td>
      <td>{{item.status}}</td>
      <td>{{item.name}}</td>
    </tr>
</table>

Used this simple JSON:

[{"id":1,"status":"active","name":"A"},
{"id":2,"status":"live","name":"B"},
{"id":3,"status":"active","name":"C"},
{"id":6,"status":"deleted","name":"D"},
{"id":4,"status":"live","name":"E"},
{"id":5,"status":"active","name":"F"}]

To render any json in tabular format:

<table>
    <thead>
      <tr>
        <th ng-repeat="(key, value) in vm.records[0]">{{key}}</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="(key, value) in vm.records">
        <td ng-repeat="(key, value) in value">
          {{value}}
        </td>
      </tr>
    </tbody>
</table>

See complete code in detail with other features


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature