我有从我的数据库返回并显示在屏幕上的行:
<tr data-ng-repeat="row in grid.data">
行包含“id”,“number”,“text”等列。
有没有任何关于如何创建下拉列表的示例,这些示例允许我选择这三列中的哪一列来按顺序排序返回的行?
答案 0 :(得分:2)
这实际上非常简单,请尝试:
<强> HTML :
<body ng-controller="AppCtrl">
Sort by: <select ng-model="sortField" ng-options="o.label for o in fields"></select>
<label>
<input type="checkbox" ng-model="inverse"> inverse
</label>
<hr>
<table>
<tr data-ng-repeat="row in grid.data|orderBy:sortField.key:inverse">
<td>{{row.id}}</td>
<td>{{row.number}}</td>
<td>{{row.text}}</td>
</tr>
</table>
</body>
<强> JS :
app.controller('AppCtrl', ['$scope', function($scope) {
$scope.fields = [
{ label: 'ID', key: 'id' },
{ label: 'Nr.', key: 'number' },
{ label: 'Text', key: 'text' }
];
$scope.sortField = $scope.fields[2];
$scope.inverse = false;
$scope.grid = {
data: [
{ id: 1, number: 4, text: 'A' },
{ id: 2, number: 3, text: 'E' },
{ id: 3, number: 2, text: 'B' },
{ id: 4, number: 1, text: 'D' },
{ id: 5, number: 0, text: 'C' }
]
};
}]);
答案 1 :(得分:1)
首先为您的订单方向定义范围变量,并通过特殊功能访问数据数组:
<div ng-app ng-controller="Ctr">
<select ng-model="orderBy">
<option>Id</option>
<option>Name</option>
</select>
<ul data-ng-repeat="row in orderData(orderBy)">
<li>{{row.Id}}: {{row.Name}}</li>
</ul>
</div>
样本控制器看起来像:
function Ctr($scope) {
// Get your data:
// (think it can be hidden in context as local variable to not to expose in
// outside because you'll access the data via special function)
var data = [
{Id: 1, Name: 'C'},
{Id: 2, Name: 'B'},
{Id: 3, Name: 'A'}
];
// Set default ordering field
$scope.orderBy = 'Id';
// Ordering function accessed from UI
$scope.orderData = function(orderBy) {
return data.sort(function(a, b) {
var valueA = a[orderBy];
var valueB = b[orderBy];
return (valueA < valueB) ? -1 : (valueA > valueB) ? 1 : 0;
});
};
}
在orderedData
控制器的功能中订购数据。