Reputation: 3717
I'm using the Angular UI-router module to navigate to a nested state.
I have a state called program
, and a state called program.dashboard
.
Whenever a user routes to program
(without providing a nested route), it should redirect to program.dashboard
. How can I tell from within the state whether it's on it's way to a nested route?
The problem I'm running into presently is that routing to any nested route under program
is causing a redirect to program.dashboard
because when the program route is evaluated, it knows nothing of the child route that is still to be loaded.
Here's something similar where the answer details the issue I'm having. They point out that you'll never be able to navigate to any state under program
other than program.dashboard
, which is exactly why I want to check to see where it's going and conditionally redirect. Angular JS ui-router how to redirect to a child state from a parent?
Any help would be appreciated.
.state('program', {
url: "/program/{programId:[0-9]{1,8}}",
templateUrl: "components-child",
controller: function($scope, $rootScope, orgService, $state,
$stateParams) {
var vm = this;
vm.curentOrganization = null;
vm.currentProgram = null;
$scope.$watch(function() {
return orgService.currentProgram();
},
function(newVal, oldVal) {
if (newVal != null) {
//this causes a redirect to program.dashboard
//even if I want to go to..say.. program.settings
$state.go('program.dashboard',
{ programId: newVal.programId });
vm.currentProgram = newVal;
}
}, true);
},
params: { programId: { value: '{{currentProgram.programId}}' } },
})
.state('program.dashboard', {
url: "/dashboard",
templateUrl: "dashboard-dashboard",
controller: 'DashboardController as vm',
})
Upvotes: 0
Views: 161
Reputation: 8216
If I understand your intent correctly, you probably want to listen for $stateChangeStart, not watch a service value.
app.run(function($state, $rootScope) {
$rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams) {
if (toState.name === 'program') {
// this is a transition directly to 'program'
event.preventDefault(); // cancel the transition
$state.go('program.dashboard', toParams); // push them to 'program.dashboard'
}
});
});
Upvotes: 0