I have an array of items and I want to render it as a table with 2 columns.
I did the basic implementation which is rendering with only one column. Any suggestions please?
<body ng-app="myApp" ng-controller="myCtrl">
<table>
<tr ng-repeat="i in items">
<td>{{i}}</td>
</tr>
</table>
</body>
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function($scope) {
$scope.items = ["12", "22", "34", "657", "129"];
});
https://jsfiddle.net/nkarri/9czrqLny/1/
This is because your HTML only has a single <td> element, which you are not repeating. Since there's only 1, you get just 1 column. You'll need to have a nested ng-repeat in the <td> element in order to get more than 1 column, or explicitly have two <td> elements defined in your HTML.
You could try to write something more complicated to try to determine when a new column or row should be created, but I'd simplify things by creating your array into something that will be a little easier to consume: essentially a 2-dimensional array. Here's what I would do instead:
<body ng-app="myApp">
<div ng-controller="myCtrl">
<table>
<tr ng-repeat="row in items">
<td ng-repeat="column in row">{{column}}</td>
</tr>
</table>
</div>
</body>
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function($scope) {
$scope.items = [];
$scope.items[0] = ["12", "22"];
$scope.items[1] = ["34", "657"];
$scope.items[2] = ["129", null];
});
https://jsfiddle.net/bntguybm/
Note that if any of these arrays were to contain more than 2 values, then you would also see extra columns for the rows that contains that data.
An alternative way would be like this, which would guarantee only 2 columns. You would need to create an array of objects for your items object. Like this:
<body ng-app="myApp">
<div ng-controller="myCtrl">
<table>
<tr ng-repeat="row in items">
<td>{{row.column1}}</td>
<td>{{row.column2}}</td>
</tr>
</table>
</div>
</body>
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function($scope) {
$scope.items = [];
$scope.items[0] = {};
$scope.items[0].column1 = "12";
$scope.items[0].column2 = "22";
$scope.items[1] = {};
$scope.items[1].column1 = "34";
$scope.items[1].column2 = "657";
$scope.items[2] = {};
$scope.items[2].column1 = "129";
$scope.items[2].column2 = null;
});
https://jsfiddle.net/6v1701gx/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With