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

All Angular2's template syntax is broken when I open the page through my hashed router

I have a hashed router that is routing from my main page just fine. The problem comes when a new page opens, all the template syntax is broken. That is all data bindings, ngFors, and even [routerLink]. So the pages open without the angular logic but…
Mostafa Fateen
  • 849
  • 1
  • 14
  • 33
12
votes
3 answers

Angular2 -- @ViewChild from TypeScript base abstract class

I was looking @ this SO Q & A, and wondering if it was possible to have a base abstract class instead? Rather than an interface, is it possible to have differing implementations of a base class in child components that are accessible to the parent…
David Pine
  • 23,787
  • 10
  • 79
  • 107
12
votes
4 answers

How to get checkbox value in angularjs?

I have a 10(or n)checkbox in my ng-view. Now I would like to ask here that What is the most efficient or simple way to check if checkbox is checked and if checked get the value of checkbox.
12
votes
3 answers

Caching URL view/state with parameters

I'm making a mobile app using Cordova and AngularJS. Currently I have installed ui-router for routing but I'm open to any other alternative for routing. My desire: I want to cache certain views bound with parameters. In other words I want to cache…
Namek
  • 1,182
  • 1
  • 13
  • 28
12
votes
1 answer

Angularjs dependency injection in resolve

I would like to use proper dependency injection in MyCtrl1to inject the fields of the MyCtrl1.resolve object. I've tried many different combinations of attempting to inject @MyCtrl1.resolve etc. with no luck. @MyCtrl1 = ($scope, $http, batman,…
jakecar
  • 586
  • 1
  • 7
  • 14
11
votes
1 answer

How to disable dynamically generated URL encoding on ` [routerLink]` in Angular 8?

I have [routerLink] as below;
  • {{ item }}
  • And…
    Teoman shipahi
    • 47,454
    • 15
    • 134
    • 158
    11
    votes
    4 answers

    Passing query parameter by using navigateByUrl()

    I am trying to Navigate to a new page on click of an icon and below is the code this.prj = e.data.project_number; this.router.navigateByUrl('/dashboard/ProjectShipment/634'); Instead of this hardcoded query parameter 000634 I have to pass a…
    trx
    • 2,077
    • 9
    • 48
    • 97
    11
    votes
    4 answers

    How to prevent full page reload when testing Angular with Cypress?

    When I write my Cypress e2e tests for my Angular application, I often use the visit() command like this: .visit('/foo/bar') This get's the job done, i.e. Cypress navigates to /foo/bar, but the entire application reloads. This is very slow, and does…
    DauleDK
    • 3,313
    • 11
    • 55
    • 98
    11
    votes
    5 answers

    ionic 4 + angular: routerLink only works first time

    I'm having a weird bug while developing a basic app from scratch right now. I use Ionic 4 beta 19 and I've put a routerLink to another page, the route is set up in the base pages module like so: RouterModule.forChild([ { path: '', component:…
    Yassine Zeriouh
    • 480
    • 3
    • 10
    • 23
    11
    votes
    1 answer

    Routing in angular - Does the order of paths matter?

    Does the order of the paths listed in app.module.ts file matters? For example... RouterModule.forRoot([ {path:'',component:HomeComponent}, {path:'followers',component:GithubFollowersComponent}, …
    psj01
    • 3,075
    • 6
    • 32
    • 63
    11
    votes
    1 answer

    How to add additional Routes dynamically in Angular

    I'm using Angular 5.2.2 (typescript) with Angular-CLI and .NET Core 2.0. I'm trying to add additional Routes dynamically to my application. The idea is that I get my routes dynamically from a server which checks what modules should be available to…
    D. Berg
    • 143
    • 1
    • 2
    • 7
    11
    votes
    2 answers

    Invalid configuration of route '': routes must have either a path or a matcher specified

    AppRouting.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { HomeComponent } from '../buyer/home/home.component'; const routes:…
    11
    votes
    2 answers

    Angular2 - APP_BASE_HREF with HashLocationStrategy

    I have an angular application uses routing with HashLocationStrategy, I need to set different value in main html file and different in routing. I tried this solution: @NgModule({ imports: [ BrowserModule, FormsModule, …
    Jarek
    • 947
    • 1
    • 7
    • 19
    11
    votes
    2 answers

    Property 'url' does not exist on type 'Event' for Angular2 NavigationEnd Event

    this.subscription = this.router.events.subscribe((event:Event) => { console.log(event.url); ##### Error : Property 'url' does not exist on type 'Event'. } Typescript doesn't recognize the properties of the type Event that is built…
    BathgateIO
    • 302
    • 1
    • 4
    • 11
    11
    votes
    6 answers

    Remove hashchange event from Angular, or prevent Angular from rewriting anchor links

    We have a project which uses Angular, but only for the UI binding/AJAX aspect of it, not for any sort of routing or SPA functionality. We want to be able to use anchor links (#section-2) in articles we write within the CMS we have chosen, as well as…
    qJake
    • 16,821
    • 17
    • 83
    • 135