Questions tagged [angular-routing]

The ngRoute module provides routing and deeplinking services and directives for AngularJS apps.

AngularJS routes enable you to create different URLs for different content in your application. Having different URLs for different content enables the user to bookmark URLs to specific content, and send those URLs to friends etc. In AngularJS each such bookmarkable URL is called a route.

AngularJS routes enables you to show different content depending on what route is chosen. A route is specified in the URL after the # sign. Thus, the following URL's all point to the same AngularJS application, but each point to different routes:

 http://myangularjsapp.com/index.html#books
 http://myangularjsapp.com/index.html#albums
 http://myangularjsapp.com/index.html#games
 http://myangularjsapp.com/index.html#apps

When the browser loads these links, the same AngularJS application will be loaded (located at http://myangularjsapp.com/index.html), but AngularJS will look at the route (the part of the URL after the #) and decide what HTML template to show.

At this point it may sound a little abstract, so let us look at a fully working AngularJS route example:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>AngularJS Routes example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
</head>

<body ng-app="sampleApp">

<a href="#/route1">Route 1</a><br/>
<a href="#/route2">Route 2</a><br/>


<div ng-view></div>

<script>
    var module = angular.module("sampleApp", ['ngRoute']);

    module.config(['$routeProvider',
        function($routeProvider) {
            $routeProvider.
                when('/route1', {
                    templateUrl: 'angular-route-template-1.jsp',
                    controller: 'RouteController'
                }).
                when('/route2', {
                    templateUrl: 'angular-route-template-2.jsp',
                    controller: 'RouteController'
                }).
                otherwise({
                    redirectTo: '/'
                });
        }]);

    module.controller("RouteController", function($scope) {

    })
</script>

Each part of this sample application will be explained in the following sections.

Including the AngularJS Route Module

The first thing to notice in the example application above is the extra JavaScript included inside the head section:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>

The AngularJS Route module is contained in its own JavaScript file. To use it we must include in our AngularJS application.

Declaring a Dependency on the AngularJS Route Module

The second thing to notice is that the applications's AngularJS module (called sampleApp) declares a dependency on the AngularJS route module:

var module = angular.module("sampleApp", ['ngRoute']);

The application's module needs to declare this dependency in order to use the ngRoute module. This is explained in more detail in my modularization and dependency injection tutorial, in the section about dependencies-between-modules.

The ngView Directive

The third thing to notice in the example above is the use of the ngView directive:

<div ng-view></div>

Inside the div with the ngView directive (can also be written ng-view) the HTML template specific to the given route will be displayed.

Configuring the $routeProvider

The fourth thing to notice in the example shown at the beginning of this text is the configuration of the $routeProvider. The $routeProvider is what creates the $route service. By configuring the $routeProvider before the $route service is created we can set what routes should result in what HTML templates being displayed.

Here is the code from the example:

<script>
    module.config(['$routeProvider',
        function($routeProvider) {
            $routeProvider.
                when('/route1', {
                    templateUrl: 'angular-route-template-1.jsp',
                    controller: 'RouteController'
                }).
                when('/route2', {
                    templateUrl: 'angular-route-template-2.jsp',
                    controller: 'RouteController'
                }).
                otherwise({
                    redirectTo: '/'
                });
        }]);
</script>

The $routeProvider is configured in the module's config() function. We pass a configuration function to the module's config() function which takes the $routeProvider as parameter. Inside this function we can now configure the $routeProvider.

The $routeProvider is configured via calls to the when() and otherwise() functions.

The when() function takes a route path and a JavaScript object as parameters.

The route path is matched against the part of the URL after the # when the application is loaded. As you can see, the two route paths passed to the two when() function calls match the two route paths in the href attribute of the links in the same example.

The JavaScript object contains two properties named templateUrl and controller. The templateUrl property tells which HTML template AngularJS should load and display inside the div with the ngView directive. The controller property tells which of your controller functions that should be used with the HTML template.

The otherwise() function takes a JavaScript object. This JavaScript object tells AngularJS what it should do if no route paths matches the given URL. In the example above the browser is redirected to the same URL with #/ as route path.

Links to Routes

The final thing to notice in this example is the two links in the HTML page:

<a href="#/route1">Route 1</a><br/>
<a href="#/route2">Route 2</a><br/>

Notice how the part of the URLs after the # matches the routes configured on the $routeProvider.

When one of these links is clicked, the URL in the browser window changes, and the div with the ngView directive will show the HTML template matching the route path.

Route Parameters

You can embed parameters into the route path. Here is an AngularJS route path parameter example:

#/books/12345

This is a URL with a route path in. In fact it pretty much consists of just the route path. The parameter part is the 12345 which is the specific id of the book the URL points to.

AngularJS can extract values from the route path if we define parameters in the route paths when we configure the $routeProvider. Here is the example $routeProvider from earlier, but with parameters inserted into the route paths:

<script>
    module.config(['$routeProvider',
        function($routeProvider) {
            $routeProvider.
                when('/route1/:param', {
                    templateUrl: 'angular-route-template-1.jsp',
                    controller: 'RouteController'
                }).
                when('/route2/:param', {
                    templateUrl: 'angular-route-template-2.jsp',
                    controller: 'RouteController'
                }).
                otherwise({
                    redirectTo: '/'
                });
        }]);
</script>

Both of the URLs in the when() calls now define a parameter. It is the part starting from the colon (:param)

AngularJS will now extract from the URL (route path) whatever comes after the #/route1/ part. Thus, from this URL:

#/route1/12345

The value 12345 will be extracted as parameter.

Your controller functions can get access to route parameters via the AngularJS $routeParams service like this:

module.controller("RouteController", function($scope, $routeParams) {
    $scope.param = $routeParams.param;
})

Notice how the controller function takes the $routeParams service as parameter, and then copies the parameter named param into the $scope.param property. Now your AngularJS views can get access to it, or you can use it in AJAX calls etc.

Here is a full AngularJS route parameter example:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>AngularJS Routes example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
</head>

<body ng-app="sampleApp">

<a href="#/route1/abcd">Route 1 + param</a><br/>
<a href="#/route2/1234">Route 2 + param</a><br/>


<div ng-view></div>

<script>
    var module = angular.module("sampleApp", ['ngRoute']);

    module.config(['$routeProvider',
        function($routeProvider) {
            $routeProvider.
                    when('/route1/:param', {
                        templateUrl: 'angular-route-template-1.jsp',
                        controller: 'RouteController'
                    }).
                    when('/route2/:param', {
                        templateUrl: 'angular-route-template-2.jsp',
                        controller: 'RouteController'
                    }).
                    otherwise({
                        redirectTo: '/'
                    });
        }]);

    module.controller("RouteController", function($scope, $routeParams) {
        $scope.param = $routeParams.param;
    })
</script>
</body>
</html>   
3260 questions
413
votes
22 answers

How to dynamically change header based on AngularJS partial view?

I am using ng-view to include AngularJS partial views, and I want to update the page title and h1 header tags based on the included view. These are out of scope of the partial view controllers though, and so I can't figure out how to bind them to…
Michael Low
  • 23,431
  • 15
  • 75
  • 115
243
votes
19 answers

How to get query parameters from URL in Angular 5?

I'm using angular 5.0.3, I would like to start my application with a bunch of query parameters like /app?param1=hallo¶m2=123. Every tip given in How to get query params from url in Angular 2? does not work for me. Any ideas how to get query…
Lars
  • 2,606
  • 2
  • 12
  • 8
193
votes
23 answers

Reloading the page gives wrong GET request with AngularJS HTML5 mode

I want to enable HTML5 mode for my app. I have put the following code for the configuration, as shown here: return app.config(['$routeProvider','$locationProvider', function($routeProvider,$locationProvider) { …
Dieter De Mesmaeker
  • 2,156
  • 2
  • 12
  • 14
179
votes
4 answers

$location / switching between html5 and hashbang mode / link rewriting

I was under the impression that Angular would rewrite URLs that appear in href attributes of anchor tags within tempaltes, such that they would work whether in html5 mode or hashbang mode. The documentation for the location service seems to say that…
laurelnaiad
  • 4,528
  • 4
  • 18
  • 18
103
votes
12 answers

How do I navigate to a parent route from a child route?

My problem is quite classic. I have a private part of an application which is behind a login form. When the login is successful, it goes to a child route for the admin application. My problem is that I can't use the global navigation menu because…
Carl Boisvert
  • 1,973
  • 3
  • 15
  • 18
100
votes
5 answers

angularjs 1.6.0 (latest now) routes not working

I was expecting to see this question on Stackoverflow but didn't. Apparently I'm the only one having this problem that seems to me to be very common. I have a basic project I am working on but the routes don't seem to work even though everything…
94
votes
5 answers

angular 4 unit testing error `TypeError: ctor is not a constructor`

I am trying to test my route resolver and while testing I got TypeError: ctor is not a constructor and no idea why it happen while typescript compile time no error. TypeError: ctor is not a constructor TypeError: ctor is not a constructor at…
Aniruddha Das
  • 14,517
  • 13
  • 83
  • 111
84
votes
3 answers

How to apply canActivate guard on all the routes?

I have a angular2 active guard which handle if the user is not logged in, redirect it to login page: import { Injectable } from "@angular/core"; import { CanActivate , ActivatedRouteSnapshot, RouterStateSnapshot, Router} from…
Nimatullah Razmjo
  • 1,318
  • 1
  • 14
  • 33
80
votes
4 answers

Best method to set different layout for different pages in angular 4

I am new to angular 4. What I'm trying to achieve is to set different layout headers and footers for different pages in my app. I have three different cases: Login, register page (no header, no footer) routes: ['login','register'] Marketing site…
ninja dev
  • 1,247
  • 2
  • 10
  • 12
72
votes
3 answers

What is the difference between ActivatedRoute and ActivatedRouteSnapshot in Angular4

What is the difference between ActivatedRouteSnapshot and ActivatedRoute in Angular 4? It's my understanding that ActivatedRouteSnapshot is a child of ActivatedRoute, meaning that ActivatedRoute contains ActivatedRouteSnapshot. Incidentally, I tried…
RajnishCoder
  • 2,429
  • 5
  • 14
  • 33
57
votes
6 answers

Angular ActivatedRoute data returns an empty object

I have a route registered with some data: const routes: Routes = [ {path: 'my-route', data: { title: 'MyTitle' }, component: MyComponent}, ]; and I'm trying to access to the route's data using ActivatedRoute: import { Component, OnInit } from…
Francesco Borzi
  • 37,945
  • 31
  • 126
  • 195
55
votes
3 answers

How to trace routing in Angular 2?

I have component with separated file of routing settings: import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { Route } from '../core/route.service'; import { extract } from…
OPV
  • 1
  • 16
  • 57
  • 124
43
votes
2 answers

Angular 4 Circular dependency detected

Upgrading Angular Cli to 1.3.1 I have some warnings now WARNING in Circular dependency detected: src\app\work-sessions\work-session-list\work-session-list.routing.ts -> src\app\work-sessions\work-session-list\index.ts ->…
Alessandro Celeghin
  • 3,161
  • 9
  • 42
  • 82
39
votes
12 answers

RouterModule.forRoot called twice

I am trying to implement Lazy Loading into my application but seem to be coming across an issue whereby I get the error message : Error: RouterModule.forRoot() called twice. Lazy loaded modules should use RouterModule.forChild() instead. So I…
Ben Clarke
  • 1,023
  • 2
  • 7
  • 13
37
votes
13 answers

Angular router: how to replace param?

Let's suppose I've got 3 urls: /:projectId/info, /:projectId/users, /:projectId/users/:userId/profile. All of them have param projectId. UI has a component to switch from one project to another. So I need: Get current URL Change param by name…
fedor.belov
  • 19,444
  • 25
  • 79
  • 121
1
2 3
99 100