I'm using ui-router
for an Angular (1.4) WebApp. Everything is fine, but the URL redirect rules. I know I can define a set of redirect rules when an URL is unknown. But I'd like to make it more advanced. I want to redirect the request to its nearest parent location.
Here is a simplified case:
/ // --> index.html
/apps/app/:id // --> app.html
/apps/app/:id/status // --> app.status.html
/unknown/path // --> no path segment is registered at all, so redirect to index.html
MY WISH:
/apps/app/:id/unknown // --> app.html (not redirect to index.html)
Here is corresponding code:
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('index', {
url: '/',
templateUrl: 'index.html'
}).
.state('app', {
url: '/apps/app/:id',
templateUrl: 'app.html'
})
.state('app.status', {
url: '/apps/app/:id/status',
templateUrl: 'app.status.html'
});
$urlRouterProvider.otherwise('/');
}])
In the real project, there are more than 20 state rules. But redirect to index.html is not user friendly. I'm looking for a smart way to redirect page to nearest page.
Now I've got a solution. Note that _.initial
comes from underscorejs.
$urlRouterProvider
.otherwise(function($injector, $location) {
var parentUrl = _.initial($location.path().split('/')).join('/');
$location.path(parentUrl);
});
You can handle more complex redirects by:
$urlRouterProvider.otherwise(function($injector, $location){
// handle each case here
});