对绑定到ID列表的AngularJS智能表进行排序

时间:2015-05-26 02:28:45

标签: angularjs smart-table

我有一个AngularJS控制器,它可以检索多个ID集合(以不同方式排序和过滤)以及将ID映射到实际数据的字典。

我正在尝试使用智能表来显示数据并允许用户对其进行排序和过滤。我遇到了如何使用智能表处理从密钥到实际数据的间接级别的麻烦。

在st-sort的示例代码中找到的解决方案是使用getter函数,但它似乎太冗长了,因为我需要单独为每个字段定义一个getter函数。此外,当数组包含标量而不是具有属性的对象时,我没有得到应该放在st-sort中的内容。

此外,我不确定智能表的其他部分是否会出现问题,因为这种间接就像过滤一样。

对于接近它的最佳方法,我将不胜感激。

控制器

 angular.module('myApp', ['smart-table'])
    .controller('mainCtrl', ['$scope',
        function ($scope) {

          $scope.ordered_ids = [ 'id-1', 'id-2', 'id-3' ];

          $scope.data = {
              'id-1': {firstName: 'Laurent', lastName: 'Renard', birthDate: new Date('1987-05-21'), balance: 102, email: 'whatever@gmail.com'},
              'id-2': {firstName: 'Blandine', lastName: 'Faivre', birthDate: new Date('1987-04-25'), balance: -2323.22, email: 'oufblandou@gmail.com'},
              'id-3': {firstName: 'Francoise', lastName: 'Frere', birthDate: new Date('1955-08-27'), balance: 42343, email: 'raymondef@gmail.com'}
          };

          $scope.getter=function (value) {
              return $scope.data[value];
          }         

        }
    ]);

HTML

<table st-table="ordered_ids" class="table table-striped">
    <thead>
      <tr>
        <th st-sort="">ID</th>
          <th st-sort="getter">First name</th>
          <th>Last name</th>
        <th>Email</th>
    </tr>
    </thead>
    <tbody>
    <tr ng-repeat="id in ordered_ids" ng-init="e = data[id]">
      <td>{{id}}</td>
        <td>{{e.firstName}}</td>
        <td>{{e.lastName}}</td>
        <td>{{e.email}}</td>
    </tr>
    </tbody>
</table>

Plunker

1 个答案:

答案 0 :(得分:0)

我认为您应首先转换数据,以便更轻松地使用

//assuming $scope.data is the object above

$scope.data = Object.keys($scope.data).map(function(key){
    return angular.extend({id:key},$scope.data[key]);
});

//no you'll have an array [{id:'id-1',fistname:'laurent',lastname:'renard', ...}, ... ]

然后一切都应该更容易

相关问题