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
11
votes
0 answers

Angular 2 access parent routeparams from child component

I've got this (main parent) component - @RouteConfig([ { path: '/', name: 'ProjectList', component: ProjectListComponent, useAsDefault: true }, { path: '/new', name: 'ProjectNew', component: ProjectFormComponent }, { path: '/:id', name:…
Lordking
  • 1,413
  • 1
  • 13
  • 31
11
votes
1 answer

Why setting $window.location.href does not work when set inside a promise?

I send request to the server and want conditionally redirect to another page (not angular) after response is received. Thus navigation happens inside then part of a promise. I tried: $location.path(url) and $window.location.href =…
Pavel Voronin
  • 13,503
  • 7
  • 71
  • 137
11
votes
1 answer

$routeChangeError not called on $q.reject

I have an Angular JS app with a Sails JS backend, and inside the routes (in app.js) I've got: .state('app.detail', { url: "/detail", views: { 'menuContent' :{ templateUrl: "templates/detail.html", controller: 'UserUpdateCtrl', …
Asaf
  • 8,106
  • 19
  • 66
  • 116
11
votes
1 answer

AngularJS - get the list of defined routes - $routeProvider

I am trying to implement named routes, so I don't have to write the whole path (often changes). I was thinking I could get away with writing a service that would return the list of defined routes and a filter that would transform object to…
g00fy
  • 4,717
  • 1
  • 30
  • 46
10
votes
4 answers

cannot find module in angular Lazy Loading

I have an angular project successfully on the Mac environment Angular CLI: 7.0.5 Node: 8.11.3 OS: darwin x64 Angular: 7.0.3 Now I am running the same code on ubuntu 18.04 with the setup Angular CLI: 7.3.9 Node: 12.9.1 OS: linux x64 Angular:…
user824624
  • 7,077
  • 27
  • 106
  • 183
10
votes
6 answers

404 Not Found error on nginx Angular: 8.0.2 routing

I am running into an issue where, when I try to access mywebsiteurl/radar-input or mywebsiteurl/daily-submissions ,I get a 404 Not Found error, I can confirm the corresponding components load fine when I don't use the routing method, following is my…
carte blanche
  • 10,796
  • 14
  • 46
  • 65
10
votes
4 answers

Angular 5 - Dynamic base reference is causing duplicate loading of bundles|chunks

I am using Angular 5.2 version in the project. I am setting the base reference dynamically in the index.html to satisfy the different URL for different clients. The app main page url looks like this :-…
Karan
  • 3,265
  • 9
  • 54
  • 82
10
votes
1 answer

c# View calling Angular component breaks, but calling Angular directly works fine

How do I fix my routing? I have a C# project with an Angular front-end. If I go to a c# View which calls an Angular component everything breaks. If I call an Angular view (directly from the URL) everything works fine. C# routing to a c# view If I…
Rilcon42
  • 9,584
  • 18
  • 83
  • 167
10
votes
3 answers

Angular router transition animations slide both left and right conditionally

I have read this article about Router transition Animations for Angular: https://medium.com/google-developer-experts/angular-supercharge-your-router-transitions-using-new-animation-features-v4-3-3eb341ede6c8 And: Angular 2 "slide in animation" of a…
Dolan
  • 1,519
  • 4
  • 16
  • 36
10
votes
1 answer

Using the in components other than the application component?

If we use the in a component (Any component) and then put a routerLink to another component within that component, does the link always render the component linked to in the of the currently active component? In other…
Ole
  • 41,793
  • 59
  • 191
  • 359
10
votes
2 answers

Angular2+ routeReuseStrategy lifecycle hooks

I'm trying to take advantage of a custom RouteReuseStrategy and for that I'd like to suspend any subscriptions when a component is detached and other things like scrolling to the proper position. I've checked for possible hooks, but apparently no…
Suau
  • 4,628
  • 22
  • 28
10
votes
6 answers

Angular - Apply style to element depending on sibling RouterLinkActive?

I do not have only one menu bar on my app that I need to be painted when the user navigates, I have another components too that needs to be painted as well. Can I achieve this just using routerLinkActive? menu.html
10
votes
3 answers

Routing not working in production

I was developing a web application in Angular 2, its working fine in my localhost, but when i hosted in production environment its not working my sub-domain is replacing with empty string My production server is http://foobar:8888/Hrms where "Hrms"…
Arjun
  • 547
  • 2
  • 6
  • 23
10
votes
1 answer

Difference between router and router-deprecated in angular2

I've updated from "beta.17" to "2.0.0-rc.1" and I don't understand when I should use router and when router-deprecated?
Illorian
  • 1,222
  • 2
  • 13
  • 38
10
votes
3 answers

How do I check for login or other status before launching a route in Angular with routeProvider?

Let's say I have 4 routes - 2 require the user to be logged in, 2 do not. My app init looks like: $routeProvider.when('/open1',{templateUrl:'/open1.html',controller:'Open1'}); …
deitch
  • 14,019
  • 14
  • 68
  • 96