我有四个表头:
$scope.headers = ["Header1", "Header2", "Header3", "Header4"];
我希望能够通过单击标题对表格进行排序。
所以如果我的桌子是这样的
H1 | H2 | H3 | H4 A H D etc.... B G C C F B D E A
然后我点击
H2
我的桌子现在看起来像这样:
H1 | H2 | H3 | H4 D E A etc.... C F B B G C A H D
也就是说,每列的内容永远不会改变,但是通过单击我要对列进行排序的标题,行将自行重新排序。
我的表的内容是通过Mojolicious完成的数据库调用创建的,并通过以下方式返回到浏览器:
$scope.results = angular.fromJson(data); // This works for me so far
我拼凑的其余代码看起来像这样:
<table class= "table table-striped table-hover"> <th ng-repeat= "header in headers"> <a> {{headers[$index]}} </a> </th> <tr ng-repeat "result in results"> <td> {{results.h1}} </td> <td> {{results.h2}} </td> <td> {{results.h3}} </td> <td> {{results.h4}} </td> </tr> </table>
从现在开始,如何通过单击表顶部的标题来对列进行排序?
我认为我创建的这个有效的CodePen示例将向您确切显示如何做所需的事情。
模板:
<section ng-app="app" ng-controller="MainCtrl"> <span class="label">Ordered By: {{orderByField}}, Reverse Sort: {{reverseSort}}</span><br><br> <table class="table table-bordered"> <thead> <tr> <th> <a href="#" ng-click="orderByField='firstName'; reverseSort = !reverseSort"> First Name <span ng-show="orderByField == 'firstName'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span> </a> </th> <th> <a href="#" ng-click="orderByField='lastName'; reverseSort = !reverseSort"> Last Name <span ng-show="orderByField == 'lastName'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span> </a> </th> <th> <a href="#" ng-click="orderByField='age'; reverseSort = !reverseSort"> Age <span ng-show="orderByField == 'age'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span> </a> </th> </tr> </thead> <tbody> <tr ng-repeat="emp in data.employees|orderBy:orderByField:reverseSort"> <td>{{emp.firstName}}</td> <td>{{emp.lastName}}</td> <td>{{emp.age}}</td> </tr> </tbody> </table> </section>
JavaScript代码:
var app = angular.module('app', []); app.controller('MainCtrl', function($scope) { $scope.orderByField = 'firstName'; $scope.reverseSort = false; $scope.data = { employees: [{ firstName: 'John', lastName: 'Doe', age: 30 },{ firstName: 'Frank', lastName: 'Burns', age: 54 },{ firstName: 'Sue', lastName: 'Banter', age: 21 }] }; });