Angular - Dynamically Choose Starting State

My app automatically starts at the default state (that has url: "/"), obviously. Let's call it state A.

I want to hold back on that in case that a certain condition is truthy. Meaning that if x === 4 for instance then I want state B to be the first one that loads.

My problem is that by the time I check for that condition, in the for instance, the default state is already being loaded and presented in the view, and only then switches to state B.

Is there any way I can hold back the state loading and kickstart it only after I check the condition ?



There is a working example

As discussed in comments we can use the native, built-in features, coming with UI-Router. One of them is $urlRouterProvider.deferIntercept(defer)

Disables (or enables) deferring location change interception.

If you wish to customize the behavior of syncing the URL (for example, if you wish to defer a transition but maintain the current URL), call this method at configuration time. Then, at run time, call $urlRouter.listen() after you have configured your own $locationChangeSuccess event handler.

I. step - STOP execution

So, we can define states in .config() phase

.config(['$stateProvider', '$urlRouterProvider','$locationProvider',
    function ($stateProvider, $urlRouterProvider,$locationProvider) {

        // States
          .state('parent', {
          .state('parent.child', { 

        // here we say STOP

II. step - init what needed in .run() - re-enable execution

This could be some naive example of run:

.run(['$urlRouter', '$timeout', '$state',
  function($urlRouter, $timeout, $state) {


      // here we turn all on again...

      // there could be some decision, driven by $http load
      // we just use some state as default target
    }, 1000)


Se do wait for a second and then we do re-enable all the execution and redirect to "parent.childd" ... but could be any other, based on some decision done in .run() phase

Check it here


Make use of resolve. if you are using ngRoute

.when('/' ,{
    templateUrl: "templates/A.html",
.when('/B' ,{
    templateUrl: "templates/B.html"
.otherwise({redirectTo: '/'});


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.