Directing the user to a child state when they are transitioning to its parent state using UI-Router
Consider the following:
.state('manager.staffList', {url:'^/staff?alpha', templateUrl: 'views/staff.list.html', data:{activeMenu: 'staff'}, controller: 'staffListCtrl'})
.state('manager.staffDetail', {url:'^/staff/{id}' , templateUrl: 'views/staff.html', data:{activeMenu: 'staff'}, controller: 'staffDetailsCtrl'})
.state('manager.staffDetail.view', {url:'/view', templateUrl: 'views/staff.details.html', data:{activeMenu: 'staff'}})
.state('manager.staffDetail.view.schedule', {url:'/schedule', templateUrl:'views/staff.view.schedule.html', data:{activeMenu: 'staff'}})
.state('manager.staffDetail.view.history', {url:'/history' , templateUrl:'views/staff.view.history.html', data:{activeMenu: 'staff'}})
.state('manager.staffDetail.view.log', {url:'/log', templateUrl:'views/staff.view.log.html', data:{activeMenu: 'staff'}})
.state('manager.staffDetail.view.files', {url:'/files', templateUrl:'views/staff.view.files.html', data:{activeMenu: 'staff'}})
.state('manager.staffDetail.edit', {url:'/edit', templateUrl: 'views/staff.edit.html', data:{activeMenu: 'staff'}})
If I go to domain.com/staff/1234/view
, how do I default to the manager.staffDetail.view.schedule
child state?
First, add a property to the
'manager.staffDetail.view'
state ofabstract:true
. This isn't required, but you want to set this since you'd never go to this state directly, you'd always go to one of it's child states.-
Then do one of the following:
-
Give the
'manager.staffDetail.view.schedule'
state an empty URL. This will make it match the same url as it's parent state url, because it appends nothing to the parent url..state('manager.staffDetail.view.schedule', {url:'', ...
-
Or if you want to keep the url of the default child route unchanged, then set up a redirect in your module.config. This code here will redirect any location of
'/staff/{id}/view'
to the location of'/staff/{id}/view/schedule'
:$urlRouterProvider.when('/staff/{id}/view', '/staff/{id}/view/schedule');
-
For setting default child view , check this example . On clicking Route 1
load default state route1.list
// For any unmatched url, send to /route1
$stateProvider
.state('route1', {
url: "/route1",
abstract:true ,
templateUrl: "route1.html"
})
.state('route1.list', {
url: '',
templateUrl: "route1.list.html",
controller: function($scope){
$scope.items = ["A", "List", "Of", "Items"];
}
})
.state('route1.desc', {
url: "/desc",
templateUrl: "route1.desc.html",
controller: function($scope){
$scope.items = [];
}
})
.state('route2', {
url: "/route2",
templateUrl: "route2.html"
})
.state('route2.list', {
url: "/list",
templateUrl: "route2.list.html",
controller: function($scope){
$scope.things = ["A", "Set", "Of", "Things"];
}
})