Javascript Angularjs-动态数据指令-从字符串创建对象

Javascript Angularjs-动态数据指令-从字符串创建对象,javascript,angularjs,parsing,angularjs-directive,Javascript,Angularjs,Parsing,Angularjs Directive,我正在编写一个指令,它表示一个用动态数据填充的表。动态数据还包括动态列数 这是我的扑克牌: 我的指令代码如下所示: app.directive("myTable", function() { return { restrict: "E", replace: true, scope: true, controller: function($scope, $element, $attrs, $http) { // Get Table Data $http.get('m

我正在编写一个指令,它表示一个用动态数据填充的表。动态数据还包括动态列数

这是我的扑克牌:

我的指令代码如下所示:

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>
我想我可以使用angular$parse,但我不确定如何实现这一点


我非常感谢您的帮助。

问题是,您存储为
key
的内容具有以下结构:
{“key”:“id”}
,因此当您执行
{items.key}
时,此items对象上没有名为key的属性

如果要显示
items.id的值,则需要
{{items[key.key]}

编辑:或者您可能只需将字符串推到
范围即可。tblKeys

$scope.tblKeys.push(key);
并在您的指令中通过以下方式访问它:

{{ items[key] }}

没问题。这真是个好主意。几年前,我不得不在服务器端使用C#和linqtosql创建一个动态生成的表。这比你拥有的代码多得多事实上,我将把你的实现与我在那个项目上共事的一个人联系起来。谢谢。不客气:)再次感谢!你不喜欢ng吗,这么小的代码:)
<td ng-repeat="key in tblKeys">  {{ items.key }}</td>
$scope.tblKeys.push(key);
{{ items[key] }}