简体   繁体   中英

Creating table from json

I have this table

<table class="table">
    <tr>
    <td ng-repeat="(k, obj) in items | orderBy:'key'">{{obj.key}}</td>
  </tr>
</table>

That shows a table of only one row with all the items in the json ($scope.items) ordered alphabetically by the key value.

Is there any way to make it so that it has a fixed number of columns, more than one row and keeps being sorted by the key value?

You need the parent index and slice up array put a tr every X times

<table class="table">
  <tr ng-repeat="trs in items" ng-if="$index % howMany == 0" ng-init="pIdx=$index">
     <td ng-repeat="(k, obj) in items.slice(pIdx,pIdx+howMany) | orderBy:'key'">{{obj.key}}</td>
  </tr>
</table>

In this example declare a variable var howMany = 6 so it will have 6 tds every row.

Try this fiddle to get yourself started

https://jsfiddle.net/U3pVM/17932/

<table class="table" ng-controller="tstCtrl">
    <tr ng-repeat="(k, obj) in items | orderBy:'key'">
        <td>{{k}}</td>
        <td>{{obj.name}}</td>
        <td>{{obj.type}}</td>
  </tr>
</table>

The short answer is yes. You need to change how you are using ng-repeat. It does not repeat the tag it is contained within, only the tags inside the ng-repeat tag.

This will show a fixed number of columns and remain sorted.

<table class="table">
  <tr>
    <th>Key</th>
    <th>Other Property</th>
  </tr>
  <tr ng-repeat="(k, obj) in items | orderBy:'key'">
    <td>{{obj.key}}</td>
    <td>{{obj.otherProperty}}</td>
  </tr>
</table>

Add the ng-repeat to the <tr> - like:

<table class="table">
    <tr ng-repeat="(k, obj) in items | orderBy:'key'">
    <td>{{obj.key}}</td>
    <td>{{obj.propertyOne}}</td>
    <td>{{obj.propertyTwo}}</td>
  </tr>
</table>

In this case, you have a three column table (add/remove columns as you wish and change the properties depending on your objects's properties

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM