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>   
3260 questions
1
vote
2 answers

make the scope values same after location.path()

On click of a button I want to change the template with the same model value. I am using location.path to change the template. Plunk- http://plnkr.co/edit/FVkSj2vs8WDAt1eifBpF?p=preview app.js var app = angular.module('includeExample',…
Eftakhar
  • 445
  • 3
  • 17
1
vote
1 answer

Should I migrate from ngRoute to ui-router?

I have a pretty extensive ngRoute router right now with around 15 different URL paths. The website I am working on displays pages with heavy data, lots of charts, etc. for a logged in user. My issue is that when I refresh the page, it will redirect…
Ariella
  • 1,055
  • 1
  • 10
  • 14
1
vote
2 answers

How do I set Page Title in AngularJS 1.4.4

I have the following html {{$scope.title}}
1
vote
2 answers

Hide param value (guid) in an URL

In my route .when('/user:user_guid',{ templateUrl : 'users/profile.html', controller : 'userController' }) In my index.html within the ng-repeat I have view profile It works but in my…
Alice Xu
  • 533
  • 6
  • 14
1
vote
1 answer

Ionic view goes blank

i'm having this problem: I have this routing schema for my Ionic app $stateProvider .state('tab', { url: '/tab', abstract: true, templateUrl: 'templates/tabs.html' }) .state('tab.plazas', { url: '/plazas', views: { …
Sebastian Hernandez
  • 1,790
  • 4
  • 21
  • 29
1
vote
1 answer

What is the difference between / and /#/?

I'm working on a small project in order to learn AngularJS. This project has two pages "/" and "/login". So, when not authenticated it redirects to "/login" and if authenticated to "/". Authentication process is handled by a NodeJS server and it…
1
vote
1 answer

How to correctly implement multiple views with UI Router in Angular?

I'm trying to implement a site with two main content 'panes' (imagine two columns each half the width of the page). The panes should be able to change independent of each other and have their own controllers and be able to pass data between each…
manihiki
  • 682
  • 2
  • 12
  • 22
1
vote
2 answers

variable not printing to screen - angularjs

I have a small controller and some basic data. Here is my code. I am not sure why when I click the link, my messages won't show. In the console, I get no errors at all. I consoled the variables, and they show up. For some reason, it doesn't work in…
LadyT
  • 539
  • 1
  • 11
  • 28
1
vote
1 answer

Failed to instantiate module in AngularJS

I am new to AngularJS and I am trying to set up angularjs routing together with a flask service but it doesn't seem to work. Here you can see the error I am getting when I run the application: Error: [$injector:modulerr]…
roniko1994
  • 51
  • 7
1
vote
1 answer

How to get the parent and child ids from location

In my url i have the id's like this: http://localhost:3000/#/projectSummary/2/3?id from this I need to get both 2 (parent id) and 3 (child id) using the $location.search how to get that both seperately. because i need to request 2 seperate query…
3gwebtrain
  • 13,401
  • 21
  • 93
  • 195
1
vote
0 answers

Angular Route Resolve -- Invoking Controller

Using angular ngRoute, I am routing request to different views/controllers. I would like to take advantage of the functionality to delay completing a route until some set of pre-requisite futures are completed. I am using the following…
jwa
  • 2,960
  • 2
  • 19
  • 48
1
vote
0 answers

URL Routing in angular 2

I'm trying to get into Angular 2, and I've gotten a working router running. The issue is that it only works when you click a router-link. If I go directly to the path then it brings up the root template, /. Here's what it looks like…
Pete.Mertz
  • 1,232
  • 1
  • 16
  • 34
1
vote
2 answers

ngRoute $injector:unpr Unknown Provider

Here is my code: var myApp = angular.module('myApp', [ 'ngRoute', 'artistControllers' ]); myApp.config(['$routeProvider', function($routeProvider) { $routeProvider. when('/list', { templateUrl: 'includes/list.html', controller:…
Long Tran
  • 63
  • 6
1
vote
2 answers

TypeScript+AngularJs:-How to define multiple routes in a single route file

I have implemented a module using typescript and angular js where i have multiple pages i want to use one typescript controller per page.than how can i define them in my routes as right now i have defined one only but what do to if i have 6 to 7…
1
vote
2 answers

What is the cleanest way to make views in the AngularJS UI-Router?

I've created this app : var accolade = angular.module('accolade', [ 'ui.router', 'personControllers', 'personFactories' ]); accolade.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider)…
1 2 3
99
100