使用选择输入对表进行排序

时间:2015-08-04 18:54:48

标签: javascript angularjs

我有以下结构:

$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 }
];

我希望使用选择输入按名称,电话或年龄对其进行排序,例如:

<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>

这就是我想出的。订单功能:

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

但它创造了另一种选择,空洞。并且我更改选择时的值未正确设置。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

我建议您将排序ng-model直接应用于orderBy过滤器,无需创建自定义函数来创建排序功能&amp;在ng-click

上调用它

还有一个建议是将选择选项转换为更合适的ng-options

<强>标记

<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>

<强>控制器

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

Working Plunkr