The ngRoute
module is a module that will allow you to configure routing in your application. Routing is listening for changes to the location and then automatically responding to those changes with a new controller and template. It uses ngView
, $routeProvider
, and $route
.
This works with the $route
service as a spot for content:
<ng-view [onload=''] [autoscroll='']/> <element ng-view [onload=''] [autoscroll='']/>
This is a provider that lets you configure routes:
$routeProvider.when(path, route) $routeProvider.otherwise(route)
path(string)
: This is what the location will be matched against. It can contain named groups by using a colon (:group
), can include a star to match multiple parts (:group*
), and can be optional (:group?
).route(object)
: This object tells Angular what to do when the route matches. The object can have these properties (not an inclusive list):controller
template
templateUrl
resolve
This is the actual service that provides which route definition has been matched. This is an object that can be injected directly into a controller.
These events can be listened for the $route
object:
$routeChangeStart
: This event is fired before the actual route change$routeChangeSuccess
: This event is fired after a route has been resolved$routeChangeError
: This event is fired if any of the route promises are rejectedThis is a service that will return the parameters of the loaded route. This will only give you parameters after a route has resolved, so you may need to use $route.current.params
. This can be injected into a controller.
Here is an example using all of the directives and services in ngRoute
. First, we have an HTML body tag. This will also include an inline template named main.html
. This template will echo out the $route
and $routeParams
objects:
<body ng-app="firstModule"> <div ng-view></div> <a href="#/main/1">Main</a> <script type="text/ng-template" id="main.html"> <pre>$routeParams = {{$routeParams}}</pre> <pre>$route = {{$route}}</pre> </script> </body>
Here is the script that will execute this. First is the creation of the module, then the configuration of $routeProvider
and, finally, the definition of a controller for the provider to use:
var firstModule = angular.module('firstModule', ['ngRoute']); firstModule.config(function ($routeProvider) { $routeProvider.when('/main/:id', { controller: 'MainController', templateUrl: 'main.html' }); }); firstModule.controller('MainController', function ($scope, $route, $routeParams) { $scope.$route = $route; $scope.$routeParams = $routeParams; });
18.226.133.49