Angular: ng-repeat 在 table 中显示顺序

Angular: ng-repeat displaying order in a table

我有一个特定的要求,json 数据是这样的:

[{Id : "a", Name : "John", age : 50},
{Id : "b", Name : "Bob", age : 40}]

我想使用 ng-repeat 在 table 中显示它,但是 headers 出现在第一列的方式如下:

<table>
  <tr>
    <td>Id</td>
    <td>a</td>
    <td>b</td>
  </tr>
  <tr>
    <td>Name</td>
    <td>John</td>
    <td>Bob</td>
  </tr>
  <tr>
    <td>Age</td>
    <td>50</td>
    <td>40</td>
  </tr>
</table>

有没有办法使用 angularjs 实现此目的?

谢谢

前提是你有控制器:

angular.module('MyApp', [])
.controller('MyController', function($scope) {
    $scope.data =  [
        {Id : "a", Name : "John", age : 50}, 
        {Id : "b", Name : "Bob", age : 40}
    ];
});

您的标记将如下所示。如果数据在显示后不会改变:

<table>
    <tr>
        <td>Id</td>
        <td ng-repeat="item in ::data">{{::item.Id}}</td>
    </tr>
    <tr>
        <td>Name</td>
        <td ng-repeat="item in ::data">{{::item.Name}}</td>
    </tr>
    <tr>
        <td>Age</td>
        <td ng-repeat="item in ::data">{{::item.age}}</td>
    </tr>
</table>

如果数据在显示后会发生变化,而您希望视图相应地更新,那么:

<table>
    <tr>
        <td>Id</td>
        <td ng-repeat="item in data track by $index">{{item.Id}}</td>
    </tr>
    <tr>
        <td>Name</td>
        <td ng-repeat="item in data track by $index">{{item.Name}}</td>
    </tr>
    <tr>
        <td>Age</td>
        <td ng-repeat="item in data track by $index">{{item.age}}</td>
    </tr>
</table>

你可以在一个对象中转换你的数组,然后你可以在视图中使用嵌套的 ng-repeats,如下所示:

(function() {
  "use strict";
  angular.module('app', [])
    .controller('mainCtrl', function($scope) {
      var array = [  
         {  
            "Id":"a",
            "Name":"John",
            "age":50
         },
         {  
            "Id":"b",
            "Name":"Bob",
            "age":40
         }
      ];
      
      // If you're sure that the properties are always these:
      $scope.mainObj = {
        "Id": [],
        "Name": [],
        "age": []
      };
     
      // If you're unsure what are the properties:
      /*
      $scope.mainObj = {};
      Object.keys(array[0]).forEach(function(value) {
        $scope.mainObj[value] = [];
      });
      */

      // Iterates over its properties and fills the arrays
      Object.keys($scope.mainObj).forEach(function(key) {
        array.map(function(value) {
          $scope.mainObj[key].push(value[key]);
        })
      });
    });
})();
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>

<body ng-controller="mainCtrl">
  <table>
    <tr ng-repeat="(key, values) in mainObj track by $index">
      <td ng-bind="key"></td>
      <td ng-repeat="value in values track by $index" ng-bind="value"></td>
    </tr>
  </table>
</body>

</html>

希望对您有所帮助!