Improve this Doc View Source

## Overview

`$route` is used for deep-linking URLs to controllers and views (HTML partials). It watches `$location.url()` and tries to map the path to an existing route definition.

Requires the `ngRoute` module to be installed.

You can define routes through $routeProvider's API.

The `$route` service is typically used in conjunction with the `ngView` directive and the `$routeParams` service.

## Dependencies

- `$location`
- `$routeParams`

## Methods

- ###

  `reload();`

  Causes `$route` service to reload the current route even if $location hasn't changed.

  As a result of that, ngView creates new scope and reinstantiates the controller.

- ###

  `updateParams(newParams);`

  Causes `$route` service to update the current URL, replacing current route parameters with those specified in `newParams`. Provided property names that match the route's path segment definitions will be interpolated into the location's path, while remaining properties will be treated as query params.

  #### Parameters

  Param | Type | Details
  --- | --- | ---
  newParams | !Object<string, string> | mapping of URL parameter names to values

## Events

- ### $routeChangeStart

  Broadcasted before a route change. At this point the route services starts resolving all of the dependencies needed for the route change to occur. Typically this involves fetching the view template as well as any dependencies defined in `resolve` route property. Once all of the dependencies are resolved `$routeChangeSuccess` is fired.

  The route change (and the `$location` change that triggered it) can be prevented by calling `preventDefault` method of the event. See `$rootScope.Scope` for more details about event object.

  #### Type:

  broadcast

  #### Target:

  root scope

  #### Parameters

  Param | Type | Details
  --- | --- | ---
  angularEvent | Object | Synthetic event object.
  next | Route | Future route information.
  current | Route | Current route information.

- ### $routeChangeSuccess

  Broadcasted after a route change has happened successfully. The `resolve` dependencies are now available in the `current.locals` property.

  ngView listens for the directive to instantiate the controller and render the view.

  #### Type:

  broadcast

  #### Target:

  root scope

  #### Parameters

  Param | Type | Details
  --- | --- | ---
  angularEvent | Object | Synthetic event object.
  current | Route | Current route information.
  previous | Route Undefined | Previous route information, or undefined if current is first route entered.

- ### $routeChangeError

  Broadcasted if a redirection function fails or any redirection or resolve promises are rejected.

  #### Type:

  broadcast

  #### Target:

  root scope

  #### Parameters

  Param | Type | Details
  --- | --- | ---
  angularEvent | Object | Synthetic event object
  current | Route | Current route information.
  previous | Route | Previous route information.
  rejection | Route | The thrown error or the rejection reason of the promise. Usually the rejection reason is the error that caused the promise to get rejected.

- ### $routeUpdate

  The `reloadOnSearch` property has been set to false, and we are reusing the same instance of the Controller.

  #### Type:

  broadcast

  #### Target:

  root scope

  #### Parameters

  Param | Type | Details
  --- | --- | ---
  angularEvent | Object | Synthetic event object
  current | Route | Current/previous route information.

## Properties

- ### `current`

  Object | Reference to the current route definition. The route definition contains: `controller`: The controller constructor as defined in the route definition. `locals`: A map of locals which is used by $controller service for controller instantiation. The `locals` contain the resolved values of the `resolve` map. Additionally the `locals` also contain: `$scope` - The current route scope. `$template` - The current route template HTML. The `locals` will be assigned to the route scope's `$resolve` property. You can override the property name, using `resolveAs` in the route definition. See $routeProvider for more info.

- ### `routes`

  Object | Object with all route configuration Objects as its properties.

## Example

This example shows how changing the URL hash causes the `$route` to match a route against the URL, and the `ngView` pulls in the partial.

    <div ng-controller="MainController">
      Choose:
      <a href="Book/Moby">Moby</a> |
      <a href="Book/Moby/ch/1">Moby: Ch1</a> |
      <a href="Book/Gatsby">Gatsby</a> |
      <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
      <a href="Book/Scarlet">Scarlet Letter</a><br/>

      <div ng-view></div>

      <hr />

      <pre>$location.path() = {{$location.path()}}</pre>
      <pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre>
      <pre>$route.current.params = {{$route.current.params}}</pre>
      <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
      <pre>$routeParams = {{$routeParams}}</pre>
    </div>

    controller: {{name}}<br />
    Book Id: {{params.bookId}}<br />

    controller: {{name}}<br />
    Book Id: {{params.bookId}}<br />
    Chapter Id: {{params.chapterId}}

    angular.module('ngRouteExample', ['ngRoute'])

     .controller('MainController', function($scope, $route, $routeParams, $location) {
         $scope.$route = $route;
         $scope.$location = $location;
         $scope.$routeParams = $routeParams;
     })

     .controller('BookController', function($scope, $routeParams) {
         $scope.name = 'BookController';
         $scope.params = $routeParams;
     })

     .controller('ChapterController', function($scope, $routeParams) {
         $scope.name = 'ChapterController';
         $scope.params = $routeParams;
     })

    .config(function($routeProvider, $locationProvider) {
      $routeProvider
       .when('/Book/:bookId', {
        templateUrl: 'book.html',
        controller: 'BookController',
        resolve: {
          // I will cause a 1 second delay
          delay: function($q, $timeout) {
            var delay = $q.defer();
            $timeout(delay.resolve, 1000);
            return delay.promise;
          }
        }
      })
      .when('/Book/:bookId/ch/:chapterId', {
        templateUrl: 'chapter.html',
        controller: 'ChapterController'
      });

      // configure html5 to get links working on jsfiddle
      $locationProvider.html5Mode(true);
    });

    it('should load and compile correct template', function() {
      element(by.linkText('Moby: Ch1')).click();
      var content = element(by.css('[ng-view]')).getText();
      expect(content).toMatch(/controller: ChapterController/);
      expect(content).toMatch(/Book Id: Moby/);
      expect(content).toMatch(/Chapter Id: 1/);

      element(by.partialLinkText('Scarlet')).click();

      content = element(by.css('[ng-view]')).getText();
      expect(content).toMatch(/controller: BookController/);
      expect(content).toMatch(/Book Id: Scarlet/);
    });