Search code examples
angularjsangular-filters

how to filter data on a table with angularjs


So, I have this table that displays users taken from a server in angularjs. Here is the users object:

'users'= [
          {
            "name":"Jane Doe",
            "gender":"female",
            "role":"admin"
          },
          {
            "name":"John Doe",
            "gender":"male",
            "role":"owner"
          }
   ]

Here is the table that displays this data:

    <div class="col-md-4">
    <h3>Filter by user role</h3>    
    <select class="form-control" ng-model="roleOrder">
            <option 
                ng-repeat="user in users" 
                value="{{user.role}}">{{user.role}}</option>
    </select>
</div>

<table class="table table-bordered">
    <thead>
        <th>Name</th>
        <th>Gender</th>
        <th>role</th>
    </thead>
    <tbody>
        <tr ng-repeat="user in users | filter:{role: roleOrder}">
            <td>{{user.name}}</td>
            <td>{{user.gender}}</td>
            <td>{{user.role}}</td>
        </tr>   
    </tbody>
</table>

The problem is, when the page loads, nothing gets displayed until I select a role from the dropdown to filter the users.

My goal is to have all the users displayed initially, and then to filter the users by their roles once their corresponding role is selected in the option select dropdown.

Is there a better way than the one I'm attempting? Or how do I do it right? Thanks for any ideas


Solution

  • You can add function for it like here AngularJS custom filter function

    In js file

    $scope.predicate = function( roleOrder ) {
      return function( item ) {
        return !roleOrder || item.role === roleOrder;
      };
    };
    

    And in html

     <tr ng-repeat="user in users | filter:predicate(roleOrder)">
            <td>{{user.name}}</td>
            <td>{{user.gender}}</td>
            <td>{{user.role}}</td>
     </tr>