Angular JS - Filter Table Rows Basis the Selection from Multiple Dropdowns

392 Views Asked by At

There is an HTML table showing employee records. Table has 4 fields: 1.) ID 2.) Name 3.) Manager 4.) Department. There are also two dropdown fields to allow filtering of records: 1.) Manager 2.) Department and by default it will show 'All' in both dropdown boxes and show all the records. But when I am selecting any value in dropdowns, its not filtering records.

Angular Code: var app = angular.module('myApp', []);

    app.controller('myCtrl', function($scope, $http) {

    $http.get('/emp').then(function(response) {
        $scope.employees = response.data;
    });

    $scope.select = function() {
          return function(emp) {
            return !$scope.selectedDep || emp.edep == $scope.selectedDep;}
        };

    $scope.managers = ['Manager 1','Manager 2'];

    $scope.department = ['TECH','HR','OPS'];});

HTML:

     <div id="detail" data-ng-app="myApp" data-ng-controller="myCtrl">

        <div class="form-group">
            <label for="selectedMgr">Manager</label><br>
            <select data-ng-model="selectedMgr" data-ng-options="mgr for mgr in managers">
                <option value="">All</option>
            </select>
        </div>

        <div class="form-group">    
            <label for="selectedDep">Department</label><br>
            <select data-ng-model="selectedDep" data-ng-options="dep for dep in department">
                <option value="">All</option>
            </select>
        </div>

    <br>

    <table class="table table-striped" id="rtable">
        <thead>
            <th>Select</th>                 
            <th>ID</th>
            <th>Name</th>
            <th>Manager</th>
            <th>Department</th>
        </thead>
        <tbody>
            <tr data-ng-repeat="emp in employees | filter:select">
                <td><input type="checkbox" /></td>
                <td>{{ emp.eid }}</td>
                <td>{{ emp.ename }}</td>
                <td>{{ emp.emgr }}</td>
                <td>{{ emp.edep }}</td> 
            </tr>
        </tbody>
    </table>        
  </div>
1

There are 1 best solutions below

2
Fernando Pinheiro On

I think your select function should actually be the function to filter the values:

> $scope.select = function(emp) { 
>     return !$scope.selectedDep || emp.edep == $scope.selectedDep; 
> }

If you do not want to change it maybe you should use it as below:

<tr data-ng-repeat="emp in employees | filter:select()">