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
1
vote
1 answer

Navigate to last visited child route when entering parent route Angular 5

In my Angular 5 application I have my router configured as this: { path: 'system-variables', component: SystemVariablesComponent, children: [ { path: '', redirectTo: 'partners-variables', …
Felipe Micali
  • 827
  • 1
  • 11
  • 25
1
vote
1 answer

Angular 2+ - Can I make a directive that makes use of router navigation?

I'm using Angular 5 and am trying to solve a problem where I have a string that looks like this: This is an herbal kind of [tea] found in the... and output something like this: This is an herbal kind of Tea
Matt Eland
  • 348
  • 1
  • 4
  • 13
1
vote
1 answer

Angular 4 redirect for my old hash URLs to new without hash URLs is not working

we have a single page application which was previously in simple tab structure where all the tab clicks has respective #urls. Examples: http://tvsntorq.com/#Price, http://tvsntorq.com/#Colour But now I have implemented this in Angular 4 and now we…
vishal kokate
  • 126
  • 3
  • 12
1
vote
0 answers

Why am I being redirected even when component class has no redirect Angular5

I am facing this weird situation. I have 3 routes in a lazy loaded module. confirm.route this.sub = this._route.params.subscribe((params: Params) => { const txn_id = params['id']; const transactions =…
LearnToday
  • 2,762
  • 9
  • 38
  • 67
1
vote
1 answer

Child route is not reached

I have the following routing structure { path: 'patients', children: [ { path: '', component: PatientsComponent }, { path: ':id', component: PatientComponent, children: [ { …
Petros Kyriakou
  • 5,214
  • 4
  • 43
  • 82
1
vote
0 answers

How to pass URL params dynamically and get relevant data from JSON object?

I have JSON data in home.ts as shown below: export class HomePage { jsonData = { "link1": "Content from link1", "link2":"Content from link2", "link3":"Content from link3" } constructor(public navCtrl:…
user2828442
  • 2,415
  • 7
  • 57
  • 105
1
vote
1 answer

Angular Routing cascade redirects (follow 2nd redirect once user has been redirected)

Have an issue (maybe just for understanding reasons) using angular router. In short when I call a route which is not allowed yet to being loaded (protected by a guard) I get redirected but if the redirect goes somewhere where a 2nd redirect is…
Bernhard
  • 4,855
  • 5
  • 39
  • 70
1
vote
2 answers

Angular child route observer

In Angular5 app I have routing defined like this: path: 'my-object/:id', component: MyObjectDetailComponent, children: [ {path: '', redirectTo: 'sublist', pathMatch: 'full'}, {path: 'sublist', component: PointComponent}, …
tester.one
  • 369
  • 2
  • 6
  • 23
1
vote
1 answer

Can Angular router expose parent – current – next routes?

I have a module which initially redirects to redirectTo: "/profile/bbb" Where profile has two children : { path: '', component: ProfileComponent, children: [{ path: 'aaa', component: AComponent }, { path:…
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
1
vote
0 answers

Angular 4 Website loading very slow with lazy loading

I am developing a website with more than 100 pages, out of which I have created approximately 50 pages. My problem is that the initial loading time of the website takes more than 30 secs to load completely. It also shows 2.8 MB data transferred when…
1
vote
1 answer

Protect api routes with tokens in a laravel - Angular application

I'm working on a application with laravel backend for API and angular for frontend. Data is feed to frontend from this API. No login (still). I want to keep these data feeding urls(routes) secure. No body cannot be access from outside. I refer this…
1
vote
2 answers

Angular 5 routing child routes

I'm quite new to Angular, and I need help regarding routing. I have this setup. app.component.html
Alan Jagar
  • 468
  • 5
  • 18
1
vote
2 answers

Angular 5 routing with nested components

OK So for sake of simplicity lets say I have 3 components: a parent component and two other components (child A and child B). I want parent component to have an url prefix of '/parent' and contain one of the two other components, component A by…
1
vote
2 answers

Angular 5 press causes unwanted refresh

When clicking on an anchor tag with a routerLink the router successfully navigates to the route but then refreshes the page. This happens on both Chrome and Edge. The anchor:
uri baum
  • 21
  • 6
1
vote
1 answer

Listening to URL changes of an angular application

I have an application which contains an iframe, the iframe is rendering an angular 4 application. I tried to listen to the iframe's URL in the following way: frame.src = appSource; frame.addEventListener('load', function () { …
Slash7GNR
  • 479
  • 4
  • 13
1 2 3
99
100