Introduction
This write-up demonstrates how to use AngularJS orderBy filter.
Getting Started
AngularJS orderBy filter allows sorting of data in a collection. It supports both, ascending and descending order. The "+" operator is used to order the data in ascending order and thde "-" operator is used to order the data in descending order. "true" and "false" are also used to order the data in ascending and descending order in collection. If no operator is mentioned, it orders the data in ascending order.
Example
- <tr ng-repeat="student in students | orderBy:+Name"> //orders in asc
- <tr ng-repeat="student in students | orderBy:-Name">//orders in desc
- <tr ng-repeat="student in students | orderBy:Name:true">//orders in asc
- <tr ng-repeat="student in students | orderBy:Name:false">//orders in desc
- <tr ng-repeat="student in students | orderBy:Name">//orders in asc
Syntax in HTML
{{ orderBy_expression | orderBy : expression : reverse : comparator}}
Example
This example displays a list of students in a table and has taken a drop-down box to order the student list in ascending or descending order. This drop-down box contains the names of columns as items, two items for each column - one for making the ascending order to the table and other for making the descending order to table.
- <HTML ng-app = "myapp">
- <TITLE> AngularJS learning(orderBy Filter)</TITLE>
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
- <script>
- var myapp=angular.module("myapp",[]);
- myapp.controller("myappcont",function($scope){
- $scope.colname=" ";
- $scope.students=[
- {Name:"Kailash",Sex:"Male",Class:"1Std",Section:"A"},
- {Name:"Kalyan",Sex:"Male",Class:"1Std",Section:"A"},
- {Name:"Kalyani",Sex:"Female",Class:"1Std",Section:"A"},
- {Name:"Kamal",Sex:"Male",Class:"2Std",Section:"B"},
- {Name:"Keshav",Sex:"Male",Class:"2Std",Section:"B"},
- {Name:"KedarGouri",Sex:"Female",Class:"2Std",Section:"B"}];
- });
- </script>
- <BODY ng-controller="myappcont">
- <h2>Student Details</h2>
- <hr/>
- <table border="1">
- <caption>
- Sort By : <select ng-model="colname">
- <option value="Name">Name Asc</option>
- <option value="-Name">Name Desc</option>
- <option value="Sex">Sex Asc</option>
- <option value="-Sex">Sex Desc</option>
- <option value="Class">Class Asc</option>
- <option value="-Class">Class Desc</option>
- <option value="Section">Section Asc</option>
- <option value="-Section">Section Desc</option>
- </select><br/><br/>
- </caption>
- <tr>
- <th>Name</input></th>
- <th>Sex</th>
- <th>Class</th>
- <th>Section</th>
- </tr>
- <tr ng-repeat="student in students | orderBy:colname">
- <td>{{student.Name}}</td>
- <td>{{student.Sex}}</td>
- <td>{{student.Class}}</td>
- <td>{{student.Section}}</td>
- </tr>
- </table>
- </BODY>
- </HTML>