christopherthielen / ui-router-extras

THIS PROJECT IS NO LONGER MAINTAINED -- Extras for UI-Router for AngularJS. Sticky States (a.k.a. parallel states), Deep State Redirect (for tab-like navigation), Future States (async state definition)
http://christopherthielen.github.io/ui-router-extras/
MIT License
917 stars 211 forks source link

How to set default inactive sticky state? #297

Closed untitledlt closed 8 years ago

untitledlt commented 8 years ago

I am using sticky states from ui-router-extras and I have two independent ui-views.

Here is my config:

$stateProvider
    .state('home', {
        url: '/',
        sticky: true,
        views: {
            'view1@': { template: 'home1' },
            'view2@': { template: 'home2' }
        }
    })
    .state('second', {
        'url': '/change-only-second-view',
        sticky: true,
        views: {
            'view2@': { template: 'view 2' }
        }
    })

When I navigate to home, both views gets updated. After navigating to /change-only-second-view only second view is updated, but now if I refresh page, I get only second view populated and first view is empty.

How can I set default view (template/controller) for first view?

christopherthielen commented 8 years ago

This plunk demonstrates one approach.

http://plnkr.co/edit/rIxTa9DyOB2jsk8lpE1h?p=preview

When the app bootstraps, it tells ui-router to wait a sec. Then it checks for any states with preload: true on them. It transitions to each preload: true state, in series, then finally tells ui-router to check the URL and route wherever it should go.

// This plunk preloads any states marked with "preload" before it allows url-routing to start
app.config(function($urlRouterProvider) {
   // This is key to delaying routing until preload is complete
  $urlRouterProvider.deferIntercept();
  // On startup, preload all the states, then activate app.modal.substate
  $urlRouterProvider.otherwise("/modal/substate");
});

app.run(function($state, $q, $urlRouter) {
  // Find all states with 'preload: true'
  var preloadStates = $state.get().filter(function(state) { return state.preload; });

  var initialPromise = $q.when(); // the start of the promise chain
  var preloadPromise = preloadStates.reduce(function (prevPromise, preloadState) {
      // builds a promise chain that goes to each "preload" state one after the other
      return prevPromise.then(function() { 
        // Chain $state.go promise on the previous promise
        return $state.go(preloadState, undefined, { 
          location: false // Don't update url
        });
      });
    }, initialPromise);

  preloadPromise.then(function() {
    // all states preloaded, now start listening for url changes.
    $urlRouter.listen();
  });
});
christopherthielen commented 8 years ago

Oh, this is in the sticky states FAQ too ;) http://christopherthielen.github.io/ui-router-extras/#/sticky