I have both routes leading to the same view and controller (i.e. I'm just passing in an id to access in $routeParams and performing controller logic on it):
$routeProvider
.when('/about',
{
controller: 'AboutController',
controllerAs: 'vm',
templateUrl: 'about.html'
})
.when('/about/:id',
{
controller: 'AboutController',
controllerAs: 'vm',
templateUrl: 'about.html'
});
This feels very repetitive. Is there any shorthand, something like this?
$routeProvider
.when(['/about', '/about/:id'],
{
controller: 'AboutController',
controllerAs: 'vm',
templateUrl: 'about.html'
})
The $routeProvider is configured with the help of calls to the when() and otherwise() functions. when() function takes route path and a JavaScript object as parameters. otherwise() takes a JavaScript object as parameters. Syntax to configure the routes in AngularJS: var app = angular.
AngularJS ngRoute module provides routing, deep linking services and directives for angular applications. We have to download angular-route. js script that contains the ngRoute module from AngularJS official website to use the routing feature. You can also use the CDN in your application to include this file.
Creating a Default Route in AngularJS The below syntax just simply means to redirect to a different page if any of the existing routes don't match. otherwise ({ redirectTo: 'page' }); Let's use the same example above and add a default route to our $routeProvider service. function($routeProvider){ $routeProvider.
To add links to one of the routes, use the routerLink directive in HTML. This directive accepts an array.
From $routeProvider
source code, it seems to me that it is not possible. this.when
method accepts two parameters, path
and route
. For multiple path, this.when
should either accept array of path as parameter, or extract multiple paths from single string. I don't see any of these two in this method.
this.when = function(path, route) {
//copy original route object to preserve params inherited from proto chain
var routeCopy = angular.copy(route);
if (angular.isUndefined(routeCopy.reloadOnSearch)) {
routeCopy.reloadOnSearch = true;
}
if (angular.isUndefined(routeCopy.caseInsensitiveMatch)) {
routeCopy.caseInsensitiveMatch = this.caseInsensitiveMatch;
}
routes[path] = angular.extend(
routeCopy,
path && pathRegExp(path, routeCopy)
);
// create redirection for trailing slashes
if (path) {
var redirectPath = (path[path.length - 1] === '/')
? path.substr(0, path.length - 1)
: path + '/';
routes[redirectPath] = angular.extend(
{redirectTo: path},
pathRegExp(redirectPath, routeCopy)
);
}
return this;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With