I am writing a directive that represents a table that gets populated with dynamic data. The dynamic data includes dynamic number of columns as well..
Here is my plunker: http://plnkr.co/edit/pmCjQL39BWWowIAgj9hP?p=preview
My directive code looks like this:
app.directive("myTable", function() {
return {
restrict: "E",
replace: true,
scope: true,
controller: function($scope, $element, $attrs, $http) {
// Get Table Data
$http.get('my-table.json').success(function(data) {
$scope.tableData = data;
console.log($scope.tableData);
$scope.tblKeys = [];
for (key in $scope.tableHeader) {
if ($scope.tableHeader.hasOwnProperty(key)) {
$scope.tblKeys.push({key: key});
}
}
console.log($scope.tblKeys);
});
},
templateUrl: "template.html",
compile: function(element, attrs) {
return function(scope, element, attrs) {
scope.css = attrs.css;
attrdata = attrs.values;
//attrdata = "{'id':'ID Col', 'name':'Name Col', 'price':'Price Col', 'qty':'Quantity'}";
convertdata = attrdata.replace(/'/g, '"');
json = JSON.parse(convertdata);
scope.tableHeader = json;
console.log(scope.tableHeader);
}; // return
} // compile
}
});
And this is the directive template
<table class="{{css}}" width="80%">
<thead>
<tr>
<th ng-repeat="title in tableHeader">
{{title}}
</th>
<th>
Cost
</th>
</tr>
</thead>
<tr ng-repeat="items in tableData">
// >>>>>>>> THIS IS WHERE I NEED HELP <<<<<<<<
<td> {{ items.id }}</td>
<td> {{ items.name }}</td>
<td> {{ items.price }}</td>
<td> {{ items.qty }}</td>
<td> {{ items.qty*items.price }}</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td colspan="2">Total</td>
</tr>
</table>
THE PROBLEM
My directive is supposed to be able to set the columns data dynamically. I have been able to get the keys of values from the table object that the directive receives as an argument but I am unable to dynamically populate the table data from the tabeData objects using dynamic keys stored into scope.tblKeys
In my template these 4 lines where I would like to avoid using id,name,price and qty and instead get that data somehow from scope.tblKeys
<td> {{ items.id }}</td>
<td> {{ items.name }}</td>
<td> {{ items.price }}</td>
<td> {{ items.qty }}</td>
Something to the tune of
<tr ng-repeat="items in tableData">
<td ng-repeat="key in tblKeys"> {{ items.key }}</td>
<td> {{ items.qty*items.price }}</td>
</tr>
I am not sure how to make this happen {{ items.key }}
and I am writing this part to illustrate what I need
<td ng-repeat="key in tblKeys"> {{ items.key }}</td>
I suppose I could use angular $parse but I am not sure how to approach this.
I would really appreciate some help.