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
21
votes
1 answer

Angular 6 child routes not working

I have a simple navigation for angular 6 app , I am trying to make routing and child routing work in a simple configuration, but unfortunately I can not seem to make it work. Here is the structure of my app └───src ├───app │ …
The Dead Man
  • 6,258
  • 28
  • 111
  • 193
21
votes
1 answer

Multiple named router-outlet angular 2

I want to display different views by child routes. For Example I want my template to hold multiple router-outlet Version: @angular/router": "3.0.0-alpha.7"
Prince
  • 291
  • 1
  • 2
  • 9
20
votes
1 answer

How to keep query parameters in angular 5 on all routes by default?

Background: The user calls the app's url with the parameters and uses my app. While switching between different routes the url parameters should be kept visible in the browser's address bar. I have to keep the query parameters on each route of my…
julianpoemp
  • 1,965
  • 3
  • 14
  • 29
20
votes
9 answers

AngularJS - Checking if a user is authenticated and then routing them to the correct page

What I am looking to do I when a user comes to the index.html page I need the login module to do 2 things: I need this to check if a user is authenticated ( which I think I already started with the "function authService" ) if the user has a valid…
agon024
  • 1,007
  • 1
  • 13
  • 37
20
votes
5 answers

Pass object as parameter in $state.go

I want to navigate to another state/screen and pass a simple json object to this next screen. I have the following: var benefit = { "x": "y"}; $state.go('pages.claimed', { 'benefit': benefit }); My state looks like this: .state('pages.claimed', { …
Jorre
  • 17,273
  • 32
  • 100
  • 145
20
votes
2 answers

Redirect index page if user is logged in AngularJS

I am trying to vary the page a user sees when they go to my website. If they are anonymous they should see the register page. If they have logged in they should see their dashboard. I have a service which checks to see if the user is logged in (e.g.…
rorymadden
  • 954
  • 3
  • 10
  • 20
19
votes
5 answers

What is the use of onSameUrlNavigation property in Angular( versions greater than 5)

Recently I have heard about a property called onSameUrlNavigation where you can set it to "reload". I have googled about it but there are not many articles which shows the use of that property. Can somebody help me with a real time example of …
ark
  • 3,707
  • 5
  • 21
  • 36
19
votes
4 answers

How can you use Angular's canActivate to negate the result of a guard?

From the Angular documentation on canActivate, it seems you can only use canActivate guards to allow proceeding to a route if the canActivate function ultimately returns true. Is there some way to say, "only proceed to this route if the canActivate…
CodyBugstein
  • 21,984
  • 61
  • 207
  • 363
19
votes
7 answers

How to apply jquery after AngularJS partial template is loaded

I have a simple website that implements jQuery in order to create a Slider with some images in the Index.html top banner. Now, I want to use AngularJS so I'm breaking the HTML code into separate partials. Header Footer Top Banner If I run the…
VAAA
  • 14,531
  • 28
  • 130
  • 253
18
votes
4 answers

use same component for different routes with different output

In my application I like to create a master (CRUD) for physician. I have a physician component for creating, editing and listing. A separate component for viewing it. I would like to URL's like physician/create physician/list physician/edit/3 So…
Abel
  • 2,371
  • 3
  • 15
  • 29
18
votes
4 answers

Angular Router Events: NavigationEnd -- How to filter only the last event

I want to extract only the last event entry of type NavigationEnd from router.events. But somehow I can't find a proper way to do this. Whatever I try the following code snipped is the only way to get access to these objects of interest. let ne:…
user6749601
18
votes
3 answers

Angular: How to get component instance of router-outlet

html: component: @Component({ selector: 'xx', templateUrl: './xx.html', styleUrls: ['./xx.css'], providers: [ RouterOutlet] }) export class AppComponent { constructor(private…
18
votes
1 answer

Partial views in AngularJS

I'm new to Angular and would appreciate any advice. Basically, I have one-to-many relationship- one Category has several Product, I have the layout page where I render different partial views:
Gyuzal
  • 1,581
  • 10
  • 52
  • 99
18
votes
3 answers

Angular UI router - access state params in parent

I have an Angular App using the great ui-router. My setup looks like: .config( function ($stateProvider, $urlRouterProvider) { $stateProvider // PROJECT DETAIL .state('project', { url: '/project/:projectId/', resolve:…
Darwin Tech
  • 18,449
  • 38
  • 112
  • 187
17
votes
5 answers

ngmodule is not a subtype ngmoduletype

I use angular 9 and I want to do lazy load and I do app-routing { path: '', loadChildren: () => import("./components/login/login.module")//.then(m => // m.LoginModule) } and after I create login module: @NgModule({ declarations:…
poopp
  • 1,297
  • 2
  • 13
  • 23