Red Cricket
Red Cricket

Reputation: 10470

How to display single column data in tabular format with angularjs?

My REST API returns hundreds rows of data that looks something like this:

[
 {"roman_number":"I"},
 {"roman_number":"II"},
 {"roman_number":"III"},
 {"roman_number":"IV"}
 {"roman_number":"V"},
 {"roman_number":"VI"},
 {"roman_number":"VII"},
 {"roman_number":"VII"},
...
 {"roman_number":"MMI"}
]

I'd like to be able to display the data in table like so ...

<table border=1>
  <tr><td>I</td><td>II</td><td>III</td><td>IV</td></tr>
  <tr><td>V</td><td>VI</td><td>VII</td><td>VIII</td></tr>
  <tr><td>IX</td><td>X</td><td>XI</td><td>XII</td></tr>
  <tr><td>XIII</td><td>XIX</td><td>XX</td><td>XXI</td></tr>
  <tr><td colspan=4> pagination here </td></tr>
 </table>

I hope that I do this in angular as I am using angular HTTP to communicate with my REST API. Thanks.

Updated based on Partha Sarathi Ghosh suggestion.

I have this app file:

var app = angular.module("myApp", ['smart-table']);

angular.module('myApp').filter('chunkby', function() {
  return function(input, chunk) {
    var i,j,temparray=[];
    if(! input ) { return; }
    for (i=0,j=input.length; i<j; i+=chunk) {
      temparray.push(input.slice(i,i+chunk));
    }
    return temparray;
  };
});

... and I have this html ...

 <table>
 <tr ng-repeat="row in (all_types|chunkby:5)">
 <td ng-repeat="col in row">{{col}}</td>
 </tr>
 </table>

... but I get this error in my console ...

Error: [$rootScope:infdig] ...

... but the data displays ok. I noticed that the plunker demo also gets this error too.

Upvotes: 2

Views: 1898

Answers (1)

Partha Sarathi Ghosh
Partha Sarathi Ghosh

Reputation: 11576

Try this custom filter

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.data = [0,1,2,3,4,5,6,7,8,9,10,11, 12,13,14,15];
});

angular.module('plunker').filter('chunkby', function() {
  return function(input, chunk) {
    var i,j,temparray=[];
    for (i=0,j=input.length; i<j; i+=chunk) {
      temparray.push(input.slice(i,i+chunk));
    }
    return temparray;
  };
});
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js" data-semver="1.4.7"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <table border=1>
      <tr ng-repeat="row in (data|chunkby:4)">
        <td ng-repeat="col in row">{{col}}</td>
      </tr>
    </table>
  </body>

</html>

Plunker Here

Upvotes: 3

Related Questions