OrderBy Filter in AngularJS


In my previous article, we demonstrated how to use filter in AngularJS. This article demonstrates how to use AngularJS orderBy filter.

Getting Started

AngularJS orderBy filter allows sorting data in collection, it supports both ascending and descending order."+" operator is used to order data in ascending order and "-" operator is used to order data in descending order. "true" and "false" also used to order data in ascending and descending order in collection. If no operator is mentioned, it orders data in ascending order


 <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}}  
Syntax in JavaScript
 $filter('orderBy')(collection, expression, reverse, comparator)  


This example displays list of students in a table and has taken a dropdownbox to order student list in ascending or descending order. This dropdownbox contains name of columns as item, it contains two items for each column. One for making ascending order to table and other from making 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>  
           var myapp=angular.module("myapp",[]);  
           $scope.colname=" ";  
      <BODY ng-controller="myappcont">  
           <h2>Student Details</h2>  
           <table border="1">  
           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>  
                <tr ng-repeat="student in students | orderBy:colname">  


In this article we have demonstrated how to use orderBy filter in AngularJS, hope this article may helpful to you. Kindly give a comment for improvement of article.

Kailash Chandra Behera

No comments:

Post a Comment