2

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

1
  • Is your users data being fetched through an async call? Commented Nov 24, 2016 at 22:31

2 Answers 2

6

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>
Sign up to request clarification or add additional context in comments.

Comments

1

user data is displaying when page loads, its working fine. Can you check the below link.

http://plnkr.co/edit/FwqivguAcyLnqxKVWEC6?p=preview

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

Is this you expectation, it not please explain it briefly. Check whether the data from server binds in $scope when the page loads

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.