I need to create a table from an array of objects but I don't want to hardcode the table. I can't do this or this for example. I rather need nested ng-repeats like this. But my case is a little bit different because I have columns which contain two values in an array. The data looks like this:
[
{
"foo":"bar",...,
"key1":[
"value1",
"value2"
],
"key2":[
"value1",
"value2"
],...,
"more_foo":"more_bar"
},...
]
I want the values (which are always strings) of all objects (which have always an equal structure) from the array in the table rows where each key should be the column name. Like this:
table,
th,
td {
border: 1px solid black;
text-align: center;
border-spacing: 0;
}
td,
th {
padding: 0.5em;
}
<table>
<thead>
<tr>
<th>foo</th>
<th colspan="2">key1</th>
<th colspan="2">key2</th>
<th>more_foo</th>
</tr>
</thead>
<tbody>
<tr>
<td>bar</td>
<td>value1</td>
<td>value2</td>
<td>value1</td>
<td>value2</td>
<td>more_bar</td>
</tr>
</tbody>
</table>
Here is what I have come up with:
<table>
<thead>
<tr>
<th ng-repeat="(propName, prop) in myArray[0]"
colspan="{{isUpdateable(propName) ? 2 : undefined}}"> {{propName}}
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="object in myArray | filter: searchFilter">
<td ng-repeat="(propName, prop) in object" double-col>{{prop}}</td>
</tr>
</tbody>
</table>
isUpdatable(propName)
will return true if this value is an array and false if it is not. This will make it possible to have two td
s in this column.
The double-col directive:
app.directive('double-col', function () {
return {
transclude: true,
template: "<td>{{prop[0]}}</td><td class=\"changedProp\">{{prop[1]}}</td>"
};
});
I want this directive to replace the existing td
with two td
s if and only if prop
is an array and otherwise do nothing to display prop
(see td
above).
Because you are on https://stackoverflow.com (the place where people post things that dont't work well yet), you can probably guess that my current code doesn't not work really well. I am also new to angularJS and have basically no understanding of custom directives (and probably most other stuff too) so it would be nice if someone could help me with this problem and provide an explanation as well.
What about
<tr ng-repeat="object in myArray | filter: searchFilter">
<td ng-repeat="(propName, prop) in object" colspan="{{isArray(prop) ? prop.length : 1}}">
<span ng-if="!isArray(prop)"> {{prop}}</span>
<table ng-if="isArray(prop)"><tr>
<td ng-repeat="prop1 in prop">
{{prop1}}
</td>
</tr></table>
</td>
</tr>
$scope.isArray=function(prop){
return Array.isArray(prop);
}