UI-Router : Prevent access to parent state

810 Views Asked by At

I am moving to UI-Router as my App router. I want to have nested state as below:

$stateProvider
.state('app', {
      url: '/app',
      template: ' <div ui-view></div>',
      authenticate: true
    })
.state('app.state1', {
      url: '/state1',
      templateUrl: 'app/state1.html',
      controller: 'State1Ctrl',
      controllerAs: 'state1',
      authenticate: true
    })
.state('app.state2', {
      url: '/state2',
      templateUrl: 'app/state2.html',
      controller: 'State2Ctrl',
      authenticate: true
    })

My $state called app is the parent of others. It only consists of a <div ui-view></div> template. It should not be accessible directly. I mean if a user enters /app in the URL, they should be redirected to `app.state1``

How can I prevent my users of doing this ?

1

There are 1 best solutions below

1
On BEST ANSWER

There is a working example

Make your state abstract:

  .state('app', {
      url: '/app',
      abstract: true, // here
      template: ' <div ui-view></div>',
      authenticate: true
    })

And add some default redirections:

  $urlRouterProvider.when('/app', '/app/state1');
  $urlRouterProvider.otherwise('/app/state1');

The first 2 links below will redirect to 'app.state1'

<a href="#/app"> // will be redirected to state1
<a href="#/app/state1">
<a href="#/app/state2">

The doc about $stateProvider:

abstract (optional) boolean

An abstract state will never be directly activated, but can provide inherited properties to its common children states.

Check it here