【发布时间】:2014-02-27 03:51:08
【问题描述】:
我正在编写一个指令,该指令表示一个填充有动态数据的表。动态数据也包括动态列数。
这是我的 plunker: http://plnkr.co/edit/pmCjQL39BWWowIAgj9hP?p=preview
我的指令代码如下所示:
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
}
});
这是指令模板
<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>
问题
我的指令应该能够动态设置列数据。我已经能够从指令作为参数接收的表对象中获取值的键,但我无法使用存储在 scope.tblKeys 中的动态键从 tabeData 对象动态填充表数据
在我的模板中,我希望避免使用 id、name、price 和 qty 的这 4 行,而是以某种方式从 scope.tblKeys 获取数据
<td> {{ items.id }}</td>
<td> {{ items.name }}</td>
<td> {{ items.price }}</td>
<td> {{ items.qty }}</td>
有什么好调的
<tr ng-repeat="items in tableData">
<td ng-repeat="key in tblKeys"> {{ items.key }}</td>
<td> {{ items.qty*items.price }}</td>
</tr>
我不知道如何做到这一点{{ items.key }},我写这部分是为了说明我需要什么
<td ng-repeat="key in tblKeys"> {{ items.key }}</td>
我想我可以使用 angular $parse 但我不知道如何处理。
非常感谢您的帮助。
【问题讨论】:
标签: javascript angularjs parsing angularjs-directive