The initial setup:
<body ng-app="myApp">
<ng-view></ng-view>
</body>
angular.module('myApp', ['ngRoute'])
.config(function($routeProvider){
$routeProvider.when("/",
{
templateUrl: "app.html",
controller: "AppCtrl",
controllerAs: "app"
}
)
.otherwise({
redirectTo: "/"
});
})
.controller('AppCtrl', function() {
var self = this;
self.message = "The app routing is working!";
});
<h1>{{ app.message }}</h1>
This demonstrates a simple and common utilization of redirectTo, where $routeProvider sees a route that doesn’t make sense, dumps off to the otherwise() case, and redirects to the root path, which could just as easily be something like a 404 page.
An alternate use of redirectTo is passing it a function instead of a route, which functions in the same way:
.when('/cookies',
{
redirectTo: function () {
return "/";
}
})
The true benefit of this format is the ability of the function to use the routeParams, path, and search arguments:
.when('/cookies',
{
redirectTo: function (routeParams, path, search) {
console.log(routeParams);
console.log(path);
console.log(search);
return "/";
}
})
The routeParams object is the same as the $routeParams used in the controller. ‘path’ is the string path the router received. ‘search’ is the key/value set of the query string parameters. This data can be used to make decisions about redirecting within the router:
.when('/cookies/:cookieType',
{
redirectTo: function (routeParams, path, search) {
console.log(routeParams);
console.log(path);
console.log(search);
return "/" + routeParams.cookieType;
}
}
)
.when('/sugar',
{
template: 'Sugar cookie'
}
)
When the router sees the ‘/cookies’ route, this will switch off to the ‘/sugar’ route when the :cookieType route parameter is ‘sugar’.