khernik
khernik

Reputation: 2091

Sort table with select input

I have the following structure:

$scope.friends = [
  { name:'John', phone:'555-1212', age:10 },
  { name:'Mary', phone:'555-9876', age:19 },
  { name:'Mike', phone:'555-4321', age:21 },
  { name:'Adam', phone:'555-5678', age:35 },
  { name:'Julie', phone:'555-8765', age:29 }
];

And I want to sort it by either name, phone, or age using select input, like that:

<select class="sortBy" ng-model="sort" ng-change="order(predicate)">
  <option value="name" ng-click="order('name')" ng-selected="predicate === 'name'">Name</option>
  <option value="phone" na-click="order('phone')" ng-selected="predicate === 'phone'">Phone</option>
  <option value="age" ng-click="order('age')" ng-selected="predicate === 'age'">Age</option>
</select>

This is what I came up with. Order function:

$scope.order = function(predicate) {
  alert(predicate);
  $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
  scope.predicate = predicate;
};

But it creates another option, empty. And the values when I change select are not set correctly. How can I do this?

Upvotes: 0

Views: 695

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136134

I'd suggest you to apply the sort ng-model directly to the orderBy filter, no need of creating custom function for creating function for sorting & calling it on ng-click

One more suggestion is to convert the select options to the ng-options that would be more proper way.

Markup

<select class="sortBy" ng-options="prop for prop in props" ng-model="sort"></select>

<table class="friend">
  <tr>
    <th>Name</th>
    <th>Phone Number</th>
    <th>Age</th>
  </tr>
  <tr ng-repeat="friend in friends | orderBy:sort">
    <td>{{friend.name}}</td>
    <td>{{friend.phone}}</td>
    <td>{{friend.age}}</td>
  </tr>
</table>

Controller

$scope.props = ["name","phone","age"]

Working Plunkr

Upvotes: 2

Related Questions