AngularJS Get Url Parameters Example
Hello readers, in this tutorial, we will understand how to retrieve the URL parameters in the angular web applications. For this tutorial, we’ll create two links on the main page and display the results based on the specified routes and the URL parameters.
1. Introduction
Before we begin with the tutorial, let’s take a look at the Angular JavaScript and its characteristics.
1.1 Angular JavaScript
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 elementsngRoute
: ThengRoute
module provides the route services for the angular web applications. In this, the route information or the form parameters are appended to the URL after the#
tagngView
: ThengView
directive display theHTML
templates or the views
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.
Th ngRoute
module makes 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 example to show how to fetch the URL parameters using the angular library.
2. AngularJS Get Url Parameters Example
Here is a step-by-step guide for implementing this tutorial 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>AngularGetUrlParameters</groupId> <artifactId>AngularGetUrlParameters</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> </project>
Let’s start building the application!
3. Application Building
Let’s start building an application to understand the basic building blocks of the ngRoute
module in the angular library.
3.1 Load the Angular 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.js"></script>
To make this tutorial ready for routing and reading the URL parameters, developers must include the angular route module reference i.e.
<script type="text/javascript" src="resource/js/angular-route.js"></script>
3.2 Define the Angular application
Next, we will define the angular application using the <ng-app>
directive.
index.jsp
<div ng-app="app"> …. </div>
3.3 Create the Angular controller
The route.js
JavaScript file has the ngRoute
dependency defined in the angular module. This dependency allows the application to has access to the routing module via the $routeProvider
attribute. The $routeProvider
attribute configures the routes. It is a simple API which has two methods i.e. when()
and otherwise()
where when()
method takes path
and route
as parameters. Here when the application is loaded, the path is matched against the part of the URL after the #
tag. If the route path matches the given URL, the browser will be redirected to the specified path. If not, the browser will be redirected to the path specified in the otherwise()
function.
This script also has an angular controller defined for the route1
routing to get the URL parameters using the $routeParams
service and display them on the result page. To understand this, the below code snippet can be used.
route.js
var app = angular.module("app", ["ngRoute"]); app.config(function ($routeProvider) { $routeProvider .when("/route1/:param1", { templateUrl: "route1.jsp", controller: 'ctrl' }) .when("/route2", { templateUrl: "route2.jsp" }); }); app.controller("ctrl", ['$scope', '$routeParams', function ($scope, $routeParams) { // Using $routeParams $scope.value1 = $routeParams.param1; }]);
3.4 Complete Application
Complete the above steps to show the front view and understand the use of ngRoute
module in angular web applications. The index page has the routes defined along with the parameters. These parameters are accessed in the angular controller via the $routeParams
service. This page has the ngView
directive defined to display the HTML
templates and will act as a placeholder for all the views provided by the route. To understand this, the below code snippet can be used.
index.jsp
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>AngularJS HttpGet Url Parameters</title> <!-- AngularJs Files --> <script type="text/javascript" src="resource/js/angular.js"></script> <script type="text/javascript" src="resource/js/angular-route.js"></script> <script type="text/javascript" src="resource/js/route.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"> </head> <body> <div id="angularHttpGetUrlParameters" class="container"> <h1 align="center" class="text-primary">AngularJS - HTTP Get Url Parameters Example</h1> <hr /> <!------ Angular Http Get() Url Parameters Example ------> <div ng-app="app"> <!-- Hyperlinks to generate templates dynamically --> <ul id="linksList" class="list-group"> <li class="list-group-item"><a id="r1Link" href="#!route1/testvalue1" class="pointer">Route 1</a></li> <li class="list-group-item"><a id="r2Link" href="#!route2" class="pointer">Route 2</a></li> </ul> <div> </div> <!-- Displays dynamic content based on the input url variables. --> <div ng-view></div> </div> </div> </body> </html>
In this, the /route1
is defined as /route1/testvalue1
i.e. followed by a variable. This is an indication for the angular routing that the values are appended to the URL and should be available in the angular controller using the $routeParams
service.
4. Run the Application
As we are ready for all the changes, let us compile the project and deploy the application on the tomcat 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 application’s index page will be displayed.
http://localhost:8080/AngularGetUrlParameters/
Server name (localhost) and port (8080) may vary as per your Tomcat configuration.
When a user clicks on any of these links, the request is sent to the browser. Here, any fragment after the #
tag gets ignored by the browser in the service call and the output is displayed.
That’s all for this post. Happy Learning!!
6. Conclusion
In this section, developers learned how to use the ngRoute
module in the angular web applications. 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 retrieving the URL parameters in the angular library.
You can download the full source code of this example here: AngularGetUrlParameters