1
votes

I have an AngularJS controller that retrieves several collections of IDs (ordered and filtered differently) and a dictionary mapping IDs to the actual data.

I am trying to use smart-table to display the data and allow the user to sort and filter it. I am having troubles with how to handle a level of indirection from key to the actual data with smart-table.

A solution found in a sample code for st-sort is to use a getter function, but it seems to be too verbose as I will need to define a getter function for each field individually. Also, I didn't get what I should put in st-sort when the array contains scalars and not objects with attributes.

Also, I am not sure if there won't be troubles with other parts of smart-table because of this indirection like with filtering.

I would appreciate any advice on the best way to approach it.

Controller

 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: '[email protected]'},
              'id-2': {firstName: 'Blandine', lastName: 'Faivre', birthDate: new Date('1987-04-25'), balance: -2323.22, email: '[email protected]'},
              'id-3': {firstName: 'Francoise', lastName: 'Frere', birthDate: new Date('1955-08-27'), balance: 42343, email: '[email protected]'}
          };

          $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

1 Answers

1
votes

I think you should transform you data first to make it easier to work with

//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', ...}, ... ]

Then everything should be easier