如何在angularjs中将Object显示为复杂的html表

时间:2016-06-30 01:48:17

标签: html angularjs angularjs-directive

我有下面的对象,我想按照下面的模板显示。有人可以指导我吗?我希望它能够简单快速地进行优化。

先谢谢。

对象

var dataSource =  [
    {
        Id: 5,
        CriteriaName: 'First Criteria',
        CustomerName: 'Customer-1',
        Points: 350, Total: 500
    },
    {
        Id: 5,
        CriteriaName: 'First Criteria',
        CustomerName: 'Customer-2',
        Points: 250,
        Total: 500
    },
    {
        Id: 5,
        CriteriaName: 'First Criteria',
        CustomerName: 'Customer-3',
        Points:150,
        Total: 500
    },
    {
        Id: 5,
        CriteriaName: 'Second Criteria',
        CustomerName: 'Customer-1',
        Points:400,
        Total: 450
    },
    {
        Id: 5,
        CriteriaName: 'Second Criteria',
        CustomerName: 'Customer-2',
        Points: 300,
        Total: 450
    },
    {
        Id: 5,
        CriteriaName: 'Second Criteria',
        CustomerName: 'Customer-3',
        Points:200,
        Total: 450
    }
];

期望的输出是:

的jsfiddle

https://jsfiddle.net/7L79dryr/1/

1 个答案:

答案 0 :(得分:2)

需要将此映射到不同的数据结构以及一组客户

 <table class='tbl'>
   <thead>
     <tr>
       <th></th>
       <th>total</th>
       <th ng-repeat="customer in customers">{{customer}}</th>          
     </tr>
   </thead>
   <tbody>
     <tr ng-repeat='(name, data) in criteria'>
       <td>{{name}}</td>
       <td>{{data.Total}}</td>
       <td ng-repeat="customer in customers">
           {{data[customer] ? data[customer]  : 'N/A' }}
       </td>
     </tr>
     </tbody>
   </table>

JS

var customers = {},
    criteria = {};

data.forEach(function(item){
   customers[item.CustomerName]=true;
   if(!criteria[item.CriteriaName]){   
      criteria[item.CriteriaName]= {Total:item.Total}
   }
   criteria[item.CriteriaName][item.CustomerName]  = item.Points;
});

$scope.customers = Object.keys(customers).sort();
$scope.criteria = criteria;

不确定Total应如何运作,我只使用了第一个可用的

DEMO