esvit / ng-table

Simple table with sorting and filtering on AngularJS
http://esvit.github.io/ng-table
BSD 3-Clause "New" or "Revised" License
2.77k stars 851 forks source link

Auto generate Select Filter #909

Open vincent-leonardo opened 8 years ago

vincent-leonardo commented 8 years ago

Just sharing a problem that I've encountered and the solution. I thought it might be a good addition to the library. Or I am just dumb to not know how to use this library properly.

I was having trouble with populating select filter-data asynchronously. I'm generating filter once my async data has been completed. But I believe the default select filter does not update the data once it's first loaded. (e.g. initializing empty filter-data and populate it after async request completed). I understand that I can pass async function/data into it, I would like to avoid it as my filter simply consist of the options available on a particular field/column. And if I were to do another async request, I would need to re-request my data (trying to minimize bandwidth and stuff).

So I thought of building a dynamic select that auto-populate the options from the available options from dataset.

dynamic-select.html

<select ng-options="$eval($column.data.id, data) as $eval($column.data.title, data) for data in params.settings().dataset | unique: $column.data.id"
        ng-table-select-filter-ds="$column"
        ng-disabled="$filterRow.disabled"
        ng-model="params.filter()[name]"
        class="filter filter-select form-control" name="{{name}}">
    <option value=""></option>
</select>

sample.html

<table ng-table="mTableParams" show-filter="true" class="table table-bordered table-striped">
    <tr ng-repeat="row in $data track by row.id">
      <td title="'Name'" filter="{name: 'text'}" sortable="'name'">{{row.name | titleCase}}</td>
      <td title="'Email'" filter="{email: 'text'}" sortable="'email'">{{row.email}}</td>
      <td title="'group'" filter="{type: 'dynamicSelect'}" filter-data="{id: 'group.id', title: 'group.name | titleCase'}" sortable="'type'">{{row.type | titleCase}}</td>
      </td>
    </tr>
  </table>

data snippet

[{
  name: 'Jason',
  email: 'jason@mail.com',
  group: {
     id: 1,
     name: 'group a'
  }, {
  name: 'James',
  email: 'james@mail.com',
  group: {
     id: 2,
     name: 'group z'
  }, {
  name: 'Brad',
  email: 'brad@mail.com',
  group: {
     id: 1,
     name: 'group a'
  }
}]

It will create a dropdown with these options:

It basically takes in id and title for its (value, label) pair. I made it such that it handles expression (dot notation for inner property, filter, sorting, etc.). It generates the options (unique) based on the given id.

Hope it helps.