简体   繁体   中英

How to add sorting on header using angularjs filter?

I want to add sorting functionality on date header, I added orderBy 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.

main.html

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM