Angular:ng-repeat在表格中显示顺序

时间:2016-07-14 02:51:29

标签: angularjs json ng-repeat

我有一个特定的要求,const_cast<>()数据是这样的:

json

我希望使用[{Id : "a", Name : "John", age : 50}, {Id : "b", Name : "Bob", age : 40}] 在表格中显示它,但是在第一列中标题出现的方式如下所示:

ng-repeat

有没有办法使用<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> 来实现这一目标?

由于

2 个答案:

答案 0 :(得分:1)

如果您有控制器:

#include <mechsys/adlbm/Domain.h>

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

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>

答案 1 :(得分:0)

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

&#13;
&#13;
(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]);
        })
      });
    });
})();
&#13;
<!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>
&#13;
&#13;
&#13;

我希望它有所帮助!