hussain hussain - 1 month ago 5
AngularJS Question

How to add sorting on header using angularjs filter?

I want to add sorting functionality on date header, I added

filter but it's breaking the column.

How can I add sorting to date header? I would like for it to be possible for the user to click the header, which should change the sorting order.


<th>{{date | orderBy: file.fileStat}}</th>
<tr ng-repeat="file in data">
<td>{{file.fileStat |date : "dd.MM.y"}}</td>
<td><button type="button" class="btn btn-primary" ng-click="downloadServerFile(file.filename)">download</button></td>


A few errors in the syntax you've attempted, but you've made a good start.

The first error is that the orderBy: applies only to the ng-repeat directive.

Let's first change <th>{{date}}</th>.

Next, let's look at ng-repeat. There's two things which are of use to us. See: OrderBy.

So we can tell it, using a String, which field to sort on, and with a boolean, whether to reverse the order or not. We can try something such <tr ng-repeat="file in data | orderBy: 'fileStat': false">.

We should also set the boolean to a variable, such that we can keep track of when the user changes it.

<tr ng-repeat="file in data | orderBy: 'fileStat': reversed">

Finally, let's have an ng-click, to allow the user to change the order. In this example, I am going to set it on the <th>.

<th ng-click="reversed = !reversed">{{date}}</th>

Please try this and let me know if you run into any errors.