João Paiva João Paiva - 5 months ago 9
AngularJS Question

How to display dynamic tables in AngularJS?

I was trying to make a dynamic table that depending how the JSON is made it loads all the data accordingly. So far I have this:

HTML responsible for creating the table:

<div class="container" ng-controller="QuotationsController as vm">
<h2>Quotations</h2>
<p>
<a href="\">Create Quotation</a>
</p>
<table class="table">
<tr ng-repeat="Quotation in vm.Quotations">
<th ng-repeat="(key,val) in Quotation"> {{ key }} </th>
</tr>
<tr ng-repeat="Quotation in vm.Quotations">
<td ng-repeat="(key,val) in Quotation"> {{ val }}</td>
<td>
<a href="\">Edit</a> |
<a href="\">Details</a> |
<a href="\">Delete</a>
</td>
</tr>
</table>




Controller:

(function () {
"use strict";

angular
.module("PPM")
.controller("QuotationsController", ["QuotationsService", QuotationsController]);

function QuotationsController(QuotationsService) {

var vm = this;

vm.Quotations = [
{
"ID": 1,
"Description": "Leaf Rake",
"Name": "GDN-0011",
},
{
"ID" : 2,
"Description": "Garden Cart",
"Name": "GDN-0023",
},
{
"ID": 5,
"Description": "Hammer",
"Name": "TBX-0048",
},
{
"ID": 8,
"Description": "Saw",
"Name": "TBX-0022",
},
{
"ID": 10,
"Description": "Video Game Controller",
"Name": "GMG-0042",
}
];
}


})();

(I have hard-coded the data in the controller for testing purposes only. I will later delete this and make calls to a Web API.)

This gives me the following result:

enter image description here

I don't want the table headers to be repeated for each Quotation that exists. I just want to display it once, but I don't know how to acess the properties without ng-repeat. How can I do this?

Answer

Either have your controller loop through the first result or have the html do it. Either way.

Html way

    <div class="container" ng-controller="QuotationsController as vm">
<h2>Quotations</h2>
 <p> 
    <a href="\">Create Quotation</a>
 </p>
 <table class="table">
     <tr >
        <th ng-repeat="(key,val) in vm.Quotations[0] "> 
          {{ key }}
        </th> 
     </tr>
     <tr ng-repeat="Quotation in vm.Quotations"> 
        <td ng-repeat="(key,val) in Quotation">
           {{ val }}
        </td> 
        <td>
            <a href="\">Edit</a> | <a href="\">Details</a> | <a href="\">Delete</a> 
        </td> 
     </tr> 
</table>
Comments