我有一个三列数据表。前两列应按字母顺序排序,但第三列(值)需要自定义排序:高,中,低或低,中,高时反转。
到目前为止,我的字母排序工作正常,但是第3列(值)的自定义排序有问题。
JS
(function(angular) {
'use strict';
angular.module('orderByExample2', [])
.controller('ExampleController', ['$scope', function($scope) {
var items = [
{name: 'name1', type: 'Web', value: 'high'},
{name: 'name2', type: 'Email', value: 'medium'},
{name: 'name3', type: 'DNS', value: 'medium'},
{name: 'name4', type: 'Web', value: 'high'},
{name: 'name5', type: 'Web', value: 'medium'},
{name: 'name6', type: 'Email', value: 'high'},
{name: 'name7', type: 'Web', value: 'low'},
{name: 'name8', type: 'FTP', value: 'low'},
{name: 'name9', type: 'Web', value: 'high'}
];
$scope.propertyName = 'value';
$scope.reverse = false;
$scope.items = items;
$scope.sortBy = function(propertyName) {
$scope.reverse = ($scope.propertyName === propertyName) ?
!$scope.reverse : false;
$scope.propertyName = propertyName;
};
}]);
})(window.angular);
HTML
<body ng-app="orderByExample2">
<div ng-controller="ExampleController">
<pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
<hr/>
<button ng-click="propertyName = null; reverse = false">Set to default</button>
<hr/>
<table class="items">
<tr>
<th>
<button ng-click="sortBy('name')">Name</button>
<span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
</th>
<th>
<button ng-click="sortBy('type')">Type</button>
<span class="sortorder" ng-show="propertyName === 'type'" ng-class="{reverse: reverse}"></span>
</th>
<th>
<button ng-click="sortBy('value')">Value</button>
<span class="sortorder" ng-show="propertyName === 'value'" ng-class="{reverse: reverse}"></span>
</th>
</tr>
<tr ng-repeat="item in items | orderBy:propertyName:reverse">
<td>{{item.name}}</td>
<td>{{item.type}}</td>
<td>{{item.value}}</td>
</tr>
</table>
</div>
</body>
Plunker:https://plnkr.co/edit/zBKd3ot22NGZd0y5XTow?p=preview
答案 0 :(得分:1)
正如@ jb-nizet所说,你将需要一个自定义函数,它将返回值来对每个元素进行排序。这是实现该功能的一种方式:
function sortingValue(e) {
return ['high', 'medium', 'low'].indexOf(e.value);
}