Reputation: 1654
I am trying to build a table with angularJS ng-repeat with double entry points. Here is an example:
Column A Column B Column C
Object 1 X Y
Object 2 P
Object 3 N
In the table above, "Object 1" has 2 sub-objects: X and Y that belong to the columns A and C respectively.
I need to be able to match the rows content to the column heading. I am not sure what what JSON structure do I need or how to use ng-repeat properly to do this ?
Upvotes: 0
Views: 1038
Reputation: 1
Without any third party tools we can use a way to achieve dynamic columns and rows.
Consider I have rows collection in $scope.rows and column collection in $scope.column.
$scope.column = [{ColumnName:"Column1"},{ColumnName:"Column2"},{ColumnName:"Column3"}]
$scope.rows = [
{"Column1":"A","Column2":"One","Column3":1},
{"Column1":"B","Column2":"Two","Column3":2},
{"Column1":"C","Column2":"Three","Column3":3},
{"Column1":"D","Column2":"Four","Column3":4},
{"Column1":"E","Column2":"Five","Column3":5}]
The html to form a table using these collection would be like this,
<table>
<thead>
<th ng-repeat="x in column">{{x.ColumnName}}</th>
</thead>
<tbody>
<tr ng-repeat="x in rows">
<td ng-repeat="y in column">{{x[y.ColumnName]}}</td>
</tr>
</tbody>
</table>
You have to add two ng-repeat. One for <tr> and another <td>.
<!-- begin snippet: js hide: false console: true babel: false -->
table {
font-family: Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
}
table td, table th {
border: 1px solid #ddd;
padding: 8px;
}
table tr:nth-child(even){background-color: #f2f2f2;}
table tr:hover {background-color: #ddd;}
table th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: darkslateblue;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<table>
<thead>
<th ng-repeat="x in column">{{x.ColumnName}}</th>
</thead>
<tbody>
<tr ng-repeat="x in rows">
<td ng-repeat="y in column">{{x[y.ColumnName]}}</td>
</tr>
</tbody>
</table>
</div>
Upvotes: 0
Reputation: 503
I would consider a third-party library, such as ngTable to handle logic like this. The Open Source Community has generally thought of great solutions for problems like this.
Your example:
controller.js
angular.module('yourmodule', ["ngTable"])
.controller('exampleController', ($scope, $service, NgTableParams) => {
// Get a JSON object from your backend of choice
$service.getObjects().then(rows => {
$scope.table_data = new NgTableParams({}, {dataset: rows})
})
})
template.html
<div ng-controller="exampleController">
<table ng-table="table_data">
<tr ng-repeat="row in $data">
<td title="ColA"></td>
<td title="ColB"></td>
<td title="ColC"></td>
</tr>
</table>
</div>
Upvotes: 1