我想点击Name,并希望它们相应地进行升序或降序排序。我尝试过$scope.listings=$scope.listings在HTML中点击,并尝试将其设为true或false,尝试将两个函数写在一个函数中,但不起作用。我需要一点帮助。
HTML
<th ng-click="setSort('Name')" style="width: 32%;"><h4>Name</h4></th>
JS-
.controller('HomeCtrl', ['$rootScope',
function ($rootScope) {
$scope.setSort = function (sort) {
$scope.resultsExist = false;
if (sort) $scope.state.sortSpec = sort;
if ($scope.state.sortSpec == 'Discount') {
discountSort();
}
else if ($scope.state.sortSpec == 'Name') {
nameSort();
}
};
function nameSort() {
$scope.listings = _.sortBy($scope.listings, function (listing) {
return listing['name'];
});
}
function reverseSort() {
$scope.listings = _.sortBy($scope.listings, function (listing) {
return listing['name'].charCodeAt('name') * -1;
});
}
}]);
假设您有一个包含数据的数组:
$scope.data = [
{name: 'John', surname: 'Smith'},
{name: 'Mary', surname: 'Andrews'},
{name: 'Ian', surname: 'Pitus'}
];
在一个简单的html表中显示为:
<table style="width:100%">
<tr>
<th><span class="sortable" ng-click="sortDataBy('name')">Name</span></th>
<th><span class="sortable" ng-click="sortDataBy('surname')">Surname</span></th>
</tr>
<tr ng-repeat="record in data">
<td>{{record.name}}</td>
<td>{{record.surname}}</td>
</tr>
</table>
并将当前排序属性(字段和顺序(保存在一个简单的对象中:
$scope.sortAttrs = {
field: null,
order: null
};
简单地将sortDataBy
功能实现为:
$scope.sortDataBy = function(field) {
$scope.sortAttrs.field = field;
$scope.sortAttrs.order = $scope.sortAttrs.order == 'asc' ? 'desc' : 'asc';
var sortDataAsc = _.sortBy($scope.data, function(o) {
return o[field];
});
$scope.data = $scope.sortAttrs.order == 'asc' ? sortDataAsc : sortDataAsc.reverse();
};
您可以在工作plunker中查看上面的实现。
添加更多的字段,如"折扣"等就足够简单了。只需为$scope.data
数组中的字段和html table
中的新列添加数据。