在HTML表格中显示对象ng-repeat - Angular

时间:2017-03-23 05:39:57

标签: javascript angularjs loops grid angularjs-ng-repeat

我的对象看起来像这样

Object
    207T : Object
        metal : 1
        steel : 2
    205T : Object
        metal : 1
        steel : 3
    208T : Object
        metal : 1
        steel : 3
    209T : Object
        metal : 0
        steel : 9   

现在这个对象需要以下面的格式显示

207T, 205T, 208T, 209T  should be in table heading which is fine

<tr>
    <th></th>
    <th></th>
    <th ng-repeat="(key, value) in mainObj">{{key}}</th>
</tr>

然后格式应为

enter image description here

如何实现这个

4 个答案:

答案 0 :(得分:2)

我们无法创建表列,因此在这种情况下,最好和最干净的方法是过滤掉行值并在视图中使用它们。所以 在控制器

ProjectName->Publish->Folder->Publish

在视图中我们只显示我们的值

app.controller(['$scope', function($scope){
  $scope.object= values;

  $scope.valuesMetal= [];
  $scope.valuessteel = [];
  // initializing row values for use in the using in view

  angular.forEach(values, function(value, key) {
     $scope.valuesMetal.push(value.metal );
     $scope.valuessteel.push(value.metal );
  }); 
}]);

答案 1 :(得分:2)

这实际上很简单。

    <table>
    <tr>    
        <th></th>
        <th ng-repeat="(key, value) in mainObj">{{key}}</th>
    </tr>

这里你重复一遍,将显示207t,205T等

    <tr ng-repeat="item in items track by $index">    
        <td ng-repeat="item1 in item track by $index">{{item[$index]}}</td>            
    </tr>

此处您必须ng repeat tr,以便显示metalsteel。然后每个td你必须ng repeat,并且应该显示索引item[$index]

答案 2 :(得分:1)

对于标题,您需要将对象转换为数组:

// inside controller
mainObjArray = Object.keys(mainObj); // ['207T', '205T', '208T', '209T']

// header html

<tr>
     <th ng-repeat="key in mainObjArray">{{key}}</th>
</tr>

对于其他值,您可以执行以下操作:

// inside controller
mainObjValues = mainObjArray.map(function(item){
  return mainObj[item];
}); // output: [{metal: 1, steel: 2}, {...}]

然后是身体表:

<tbody>
  <tr ng-repeat="item in mainObjValues">
   <td>{{item.metal}}</td>
   <td>{{item.steel}}</td>
   ....
  </tr>
</tbody>

答案 3 :(得分:1)

angular.module("app",[])
.controller("ctrl",function($scope){
var sampleObj = {  
   "207T":{  
      "metal":1,
      "steel":2
   },
   "205T":{  
      "metal":1,
      "steel":3
   },
   "208T":{  
      "metal":1,
      "steel":3
   },
   "209T":{  
      "metal":0,
      "steel":9
   }
}
 $scope.metal = [];
 $scope.steel= []
$scope.keys = Object.keys(sampleObj);

angular.forEach(sampleObj, function(obj) {
     $scope.metal.push(obj.metal );
     $scope.steel.push(obj.steel );
  }); 

})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="ctrl">
<table>
 
 <tr>
    <th ng-repeat="item in keys">{{item}}</th> 
</tr> 
<tr>
    <td >Metal</td>
    <td  ng-repeat="item in metal track by $index" >{{item}}</td>

</tr>

<tr>
    <td >Steel</td>
    <td  ng-repeat="item in steel track by $index" >{{item}}</td>

</tr>
</table>
</div>