Javascript AngularJS-使用下划线对表列进行排序
我想点击名称,并希望他们相应地升序或降序排序。我尝试了$scope.listings=$HTML ng中的scope.listings单击并尝试将其设置为true或false,尝试将两个函数都写在一个函数中,但都不起作用。我需要一点帮助 HTMLJavascript AngularJS-使用下划线对表列进行排序,javascript,html,angularjs,Javascript,Html,Angularjs,我想点击名称,并希望他们相应地升序或降序排序。我尝试了$scope.listings=$HTML ng中的scope.listings单击并尝试将其设置为true或false,尝试将两个函数都写在一个函数中,但都不起作用。我需要一点帮助 HTML 假设您有一个包含数据的数组: $scope.data = [ {name: 'John', surname: 'Smith'}, {name: 'Mary', surname: 'Andrews'}, {name: 'Ian', surna
假设您有一个包含数据的数组:
$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>
只需将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();
};
您可以在中查看上述实现
添加更多字段(如“折扣”等)非常简单。只需为$scope.data
数组中的字段添加数据,并在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
};
$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();
};