Phoenix Phoenix - 2 months ago 6
AngularJS Question

Issue with filtering an Angular Table td

I have a table created in angularJS.

HTML:

<div class="widget-content" ng-controller="getAllBenchersController">
<table ng-table="talentPoolList" show-filter="true"
class="table table-striped table-bordered">
<tr ng-repeat="employee in $data" | filter: testFilter">
<td data-title="'#'">{{$index + 1}}</td>
<td data-title="'Employee ID'" sortable="'employee.employeeNo'"
filter="{ 'employee.employeeNo': 'text' }">
{{employee.employee.employeeNo}}
</td>
<td data-title="'Current State'" sortable="'state.state'" filter="{ 'state.state': 'text' }"
ng-class="{ red: employee.state.state == 'Available', blue: employee.state.state == 'Blocked'}">
{{employee.state.state}}
</td>
</tr>
</table>
</div>


In the
<td data-title="'Current State'">
I want to apply a filter. I want to display only states returning values 'Available' and 'Blocked'.

My controller is :

myApp.controller('getAllBenchersController', ['$scope', 'employeeTalentPoolServices', 'dataTable', '$window', '$timeout', function ($scope, employeeTalentPoolServices, dataTable, $window, $timeout) {
employeeTalentPoolServices.getAllBenchers().then(function (result) {
$scope.data = result.data;
$scope.testFilter = function (item) {
return (item.state.state.toLowerCase() === 'available' || item.state.state.toLowerCase() === 'blocked');
}
});


The states generally return values -'Available', 'Blocked', 'Billed' and 'Rejected'. I want the table to only display states - 'Available' and 'Blocked'.
Please have a check and point out what I'm doing wrong.

Answer

If you want to display only the items with the state 'available' and 'blocked' i think the best choice is to apply an angular filter in the ng-repeat. By this way, the ng-repeat only computes the items needed for the table.

You can add a new filter, for example:

myApp.filter('filterState',
  [], function() {
      return function(items) {
        return items.map(function(obj) {
          if (obj.state === 'available' || obj.state === 'blocked')
             return obj;
        });
});

After, your div element should be:

<tr ng-repeat="employee in $data" | filter: filterState">