AngularJS orderBy Multiple Fields Example
Hello readers, in this tutorial, we will learn how to implement and use the orderBy filter in the angular web applications.
1. Introduction
Angular is a JavaScript MVC or Model-View-Controller framework developed by Google that lets developers build well structured, easily testable, and maintainable front-end applications. But before we start creating a real application using the angular library, let us see what the important parts of an angular application are.
1.1.1 Templates
In Angular, a template is an HTML
with added markups. The angular library compiles the templates and renders the resultant HTML
page.
1.1.2 Directives
Directives are the markers (i.e. attributes) on a DOM element that tell angular to attach a specific behavior to that DOM element or even transform the DOM element and its children. Most of the directives in the angular library start with the ng
. The directives consist of the following parts:
ng-app
: Theng-app
directive is a starting point. If the angular framework finds theng-app
directive anywhere in theHTML
document, it bootstraps (i.e. initializes) itself and compiles theHTML
templateng-model
: Theng-model
directive binds anHTML
element to a property on the$scope
object. It also binds the values of angular application data to theHTML
input controlsng-bind
: Theng-bind
directive binds the angular application data to theHTML
tagsng-controller
: Theng-controller
directive specifies a controller in the HTML element. This controller will add behavior or support the data in that HTML element and its child elements
1.1.3 Expressions
An expression is like a JavaScript code usually wrapped inside the double curly braces such as {{ expression }}
. Angular library evaluates the expression and produces a result.
1.2 What are Angular filters?
In an angular library, filters allow transforming the data to be displayed on the UI without changing the original format. Angular filters are implemented in the angular directives and expressions using the pipe character (i.e. |
). Following is the basic syntax using the angular filter in an angular application.
Angular filter basic syntax
{{ expression | filterName:parameter }}
1.2.1 Order-by Filter
This filter sorts an array according to the specified condition, e.g. ascending or descending. Following is the syntax of using the orderBy filter in angular applications.
Syntax
{{ orderBy_expression | orderBy : predicate_expression : reverse }}
These new APIs make developer’s life easier, really! But it would be difficult for a beginner to understand this without an example. Therefore, let us create a simple application using the orderBy
filter.
2. AngularJS orderBy Multiple Fields Example
Here is a step-by-step guide for implementing the orderBy
filter in the angular web applications.
2.1 Tools Used
We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.
2.2 Project Structure
Firstly, let’s review the final project structure if you are confused about where you should create the corresponding files or folder later!
2.3 Project Creation
This section will show how to create a Java-based Maven project with Eclipse. In Eclipse Ide, go to File -> New -> Maven Project
.
In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.
Select the ‘Maven Web App’ Archetype from the list of options and click next.
It will ask you to ‘Enter the group and the artifact id for the project’. We will enter the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT
.
Click on Finish and the creation of a maven project is completed. If you see, it has downloaded the maven dependencies and a pom.xml
file will be created. It will have the following code:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>AngularOrderBy</groupId> <artifactId>AngularOrderBy</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> </project>
Let’s start building the application!
3. Application Building
Let’s create an application to understand the basic building blocks of the ng-click
directive in the angular library.
3.1 Load the AngularJS framework
Since it is a pure JavaScript framework, we should add its reference using the <script>
tag.
<script type="text/javascript" src="resource/js/angular_v1.6.0.js"></script>
3.2 Define the AngularJS application
Next, we will define the angular application using the <ng-app>
and <ng-controller>
directive.
index.jsp
<div ng-app="app" ng-controller="ctrl"> ..... </div>
3.3 Creating an AngularJS Controller
The JavaScript file i.e. orderby.js
has a function which includes the ctrl
function as the “controller” in the Model-View-Controller. The function will initialize a default planet list and the sorting order. Add the following code to this file:
orderby.js
var app = angular.module("app", []); app.controller("ctrl", function($scope) { $scope.orderProp = 'id'; // Set the default sort type $scope.direction = false; // Set the default sort order // Set the default planet_list $scope.json_data = [{ "id": "1", "name": "Mercury", "distancefromsun": "35.98 million mi", "lightyears": "3 light minutes", "moons": "0" }, { "id": "2", "name": "Venus", "distancefromsun": "67.24 million mi", "lightyears": "6 light minutes", "moons": "0" }, { "id": "3", "name": "Earth", "distancefromsun": "92.96 million mi", "lightyears": "8 light minutes", "moons": "1" }, { "id": "4", "name": "Mars", "distancefromsun": "141.6 million mi", "lightyears": "12.5 light minutes", "moons": "2" }, { "id": "5", "name": "Jupiter", "distancefromsun": "483.8 million mi", "lightyears": "43 light minutes", "moons": "69" }, { "id": "6", "name": "Saturn", "distancefromsun": "888.2 million mi", "lightyears": "79 light minutes", "moons": "2" }, { "id": "7", "name": "Uranus", "distancefromsun": "1.784 billion mi", "lightyears": "160 light minutes", "moons": "27" }, { "id": "8", "name": "Neptune", "distancefromsun": "35.98 million mi", "lightyears": "250 light minutes", "moons": "14" }, { "id": "9", "name": "Pluto", "distancefromsun": "3.68 billion mi", "lightyears": "327 light minutes", "moons": "5" } ]; // This method will sort the column_list based on the sort_order $scope.sort = function(column_name) { if ($scope.orderProp === column_name) { $scope.direction = !$scope.direction; } else { $scope.orderProp = column_name; $scope.direction = false; } }; });
3.4 Complete Application
Complete the above steps and I will show you how to implement this example. Let’s see the simple HTML
code snippet to understand the usage of orderBy
filter in the angular web applications.
index.jsp
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>AngularJS OrderBy</title> <!-- AngularJs File --> <script type="text/javascript" src="resource/js/angular_v1.6.0.js"></script> <script type="text/javascript" src="resource/js/orderby.js"></script> <!-- Bootstrap Css --> <link rel="stylesheet" href="https://www.webcodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9tYXhjZG4uYm9vdHN0cmFwY2RuLmNvbS8=bootstrap/4.0.0/css/bootstrap.min.css"> <style type="text/css"> th, td { text-align: center; } th a { cursor: pointer; text-decoration: none !important; } .highlight { background-color: #F8F8F8; } </style> </head> <body> <div id="angularOrderby" class="container"> <h1 align="center" class="text-info">AngularJS - orderBy Example</h1> <hr /> <!------ AngularJs 'orderBy' Example ------> <div ng-app="app" ng-controller="ctrl"> <h4 id="header_msg" class="text-muted">A demo of <em>orderBy</em> filter in Angular JavaScript!</h4> <div> </div> <table id="planetTable" class="table"> <thead> <tr> <th scope="col"><a href="#" ng-click="sort('id')">Planet Id</a></th> <th scope="col"><a href="#" ng-click="sort('name')">Planet / Star</a></th> <th scope="col">Distance from Sun</th> <th scope="col">Light Years</th> <th scope="col"><a href="#" ng-click="sort('moons')">Moons Count?</a></th> </tr> </thead> <tbody> <tr ng-repeat="row in json_data | orderBy:orderProp:direction" ng-class="rollClass" ng-mouseenter="rollClass = 'highlight'" ng-mouseleave="rollClass = ''"> <td>{{ row.id }}</td> <td>{{ row.name }}</td> <td>{{ row.distancefromsun }}</td> <td>{{ row.lightyears }}</td> <td>{{ row.moons }}</td> </tr> </tbody> </table> </div> </div> </body> </html>
4. Run the Application
As we are ready for all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server
.
Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it in the browser.
5. Project Demo
Open your favorite browser and hit the following URL. The output page using the orderBy
filter will be displayed.
http://localhost:8080/AngularOrderBy/
Server name (localhost) and port (8080) may vary as per your Tomcat configuration.
Here, as shown in Fig. 7 users can click on the column names to sort (i.e. ascending or descending order) the data. That’s all for this post. Happy Learning!!
6. Conclusion
In this tutorial, developers learned how to create a simple angular application using the orderBy
filter. Developers can download the sample application as an Eclipse project in the Downloads section.
7. Download the Eclipse Project
This was a tutorial of the order by functionality in the angular library.
You can download the full source code of this example here: AngularOrderBy