在表中动态添加列

时间:2018-01-16 17:29:17

标签: javascript jquery angularjs

我正在尝试在表中动态添加新列。我有以下对象,它是从we​​b服务api响应返回的。如何显示动态列,其中myArray对象附加了许多其他字段(新列)

 $scope.myArray =  [
    {
  "contacts": [
    {
      "id": "1",
      "contact": {
        "name": "Sam",
        "Email": "ddd@co.com",
        "PhoneNo": 2355
      }
    },
    {
      "id": "2",
      "contact": {
        "name": "John",
        "Email": "test@co.com",
        "PhoneNo": 2355
      }
    }
  ]
}
  ];

我试过调查google中一些答案中提供的示例。在我的JSFIDDLE下面,我只获得了关键名称而不是值。如何在键名称是动态的情况下使用ng-repeat来实现键和值。

1 个答案:

答案 0 :(得分:1)

angular.module('myApp', [])
  .controller('myController', function($scope) {
    $scope.myArray =  [
    {
  "contacts": [
    {
      "id": "1",
      "contact": {
        "name": "Sam",
        "Email": "ddd@co.com",
        "PhoneNo": 2355
      }
    },
    {
      "id": "2",
      "contact": {
        "name": "John",
        "Email": "test@co.com",
        "PhoneNo": 2355
      }
    }
  ]
}
  ];
  });

angular.element(document).ready(function() {
  angular.bootstrap(document, ['myApp']);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.12/angular.min.js"></script>
<table ng-controller="myController" border="1">
  <tr>
    <th ng-repeat="(key, val) in myArray[0].contacts[0].contact">{{ key }}</th>
  </tr>
  <tr ng-repeat="row in myArray[0].contacts">
    <td ng-repeat="(key, val) in row.contact">{{ val }}</td>
  </tr>
</table>