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>   
3648 questions
17
votes
1 answer

Angular 2: Redirect route with parameters and optional parameters

I want to redirect a route to another route: /foo/bar/123 schould redirect to /bar/123;mode=test I configured the route in the following way: { path: 'foo/bar/:id', redirectTo: '/bar/:id;mode=test' }, When it is redirecting, the ;mode=test part is…
Johni
  • 2,933
  • 4
  • 28
  • 47
17
votes
1 answer

state provider and route provider in angularJS

Below is my app.js file angular .module('repoApp', [ 'ngAnimate', 'ngAria', 'ngCookies', 'ngMessages', 'ngResource', 'ngRoute', 'ngSanitize', 'ngTouch', 'ui.bootstrap', 'ui.router' ]) .config(function…
Shah Rukh K
  • 559
  • 1
  • 5
  • 19
16
votes
8 answers

How to prevent page refresh in angular 4

I want to prevent page refresh by everywhere. I tried the code below import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { CommonServices } from '../services/common.service'; @Component({ …
RajnishCoder
  • 3,455
  • 6
  • 20
  • 35
16
votes
4 answers

Routing to sub routing module without lazy loading

I want to have multiple routing modules in order to keep my application clean and easy to read. I currently use lazy loading for the SubComponent but I don't want to do this. So I am looking for a way to change this. Anyways, here is the currently…
Spurious
  • 1,903
  • 5
  • 27
  • 53
16
votes
2 answers

ngOnInit not being called after router.navigate

My Angular app is all of a sudden not calling ngOnInit() after router.navigation() which means my components do not load correctly. I thought it may have been due to some changes I made but reverting the changes did not resolve the issue. Example…
Mika571
  • 332
  • 3
  • 13
16
votes
4 answers

Angular 4 Multiple Guards - Execution Sequence

I have 2 guards, AuthGuard and AccessGuard in the application. AuthGuard protects all the pages as the name suggests and stores the session object in the GlobalService and AccessGuard depends on the some access data in session object stored by…
Akul Narang
  • 331
  • 1
  • 2
  • 10
16
votes
1 answer

Routing in Angular2 - Link "['Name']" does not resolve to a terminal instruction

I am trying to get a simple app working with child routing. When I setup the routes on my child component I get the following error message: Link "["ChildItem"]" does not resolve to a terminal instruction If I place all the routes on the parent…
John
  • 237
  • 2
  • 6
16
votes
4 answers

Angular new router - Nested components and routing

I'm playing around with the new angular router and wanted to try out a use case where I have a component and a nested component. Below there's the JavaScript code I wrote to define the two components and the routes: angular.module('app',…
Alain
  • 881
  • 8
  • 14
16
votes
3 answers

How do I throw a real 404 or 301 with an Angular pushstate URL

I'm using $routeProvider and $locationProvider to handle pushstate URLS in a single page app (SPA), something like this: angular.module('pets', []) .config(function($routeProvider, $locationProvider) { $locationProvider.html5Mode(true); …
superluminary
  • 47,086
  • 25
  • 151
  • 148
16
votes
4 answers

Angular UI Router - Views in an Inherited State

edit: Based on the answer by @actor2019 I want to update my question to better explain the problem: Using Angular UI-Router(v0.0.2), I've setup the app to properly navigate between main "pages"/state, while inheriting the base…
JT703
  • 1,311
  • 4
  • 17
  • 41
15
votes
3 answers

Angular Routing: Is it possible to use different 'path' strings for different languages?

I'm doing an i18n Angular app, so far it works great. However I have same route strings for different languages, which isn't best for SEO. Is it possible to have 'path' properties of Routes array be different for each language? Ex: const…
Bogac
  • 3,596
  • 6
  • 35
  • 58
15
votes
5 answers

how to pass route params in [routerLink] angular 2

I'm trying to create an application with angular 2,And Want pass params to tag a in [routerLink],i want craete a link like this : i dont know how to pass cell in template...
user5738822
15
votes
7 answers

How to remove the hash # from the angularjs ng-route

I am trying to use the locationProvider to remove the hashtag from the url routes in angular js but it gives me error. app.js var eclassApp = angular.module('eclassApp', ['ngRoute', 'eclassControllers',…
Apostolos
  • 7,763
  • 17
  • 80
  • 150
14
votes
2 answers

What is the best way to get current route params in Angular 6 services?

I am trying to find out what is the best way to get the current route params in Angular 6. At the moment I have to pass the ActivatedRoute to the service's method as argument and then use it in the service. export class MainComponent { …
SMH
  • 889
  • 3
  • 11
  • 30
14
votes
4 answers

Angular 5/6: protect route (route guard) without redirecting to error route

I have a bit of a pickle. I am using Route guard (implementing CanActivate interface) to check if user is granted access to particular route: const routes: Routes = [ { path: '', component: DashboardViewComponent }, { …
Ivan Hušnjak
  • 3,493
  • 3
  • 20
  • 30