0

Below is a sample state hierarchy,

.state('home', {
  url: '/home',
  templateUrl: 'views/home.html',
  controller: 'HomeCtrl'
})
.state('home.books', {
  url: '/:collectionId',
  abstract: true,
  controller: 'BooksCtrl'
})
.state('home.books.displaybooks', {
  url: '^/books',
  templateUrl: 'views/displaybooks.html',
  controller: 'DisplayBookCtrl'
})

In home.books.displaybooks state, I display the collection of books.

I can access this state by two means,

  1. By clicking on the link in "home" state. I use ui-sref and pass the default collection id for the user. No problems here
  2. By URL routing http://localhost/books (please note the ^ in url in state definition. I want absolute url without displaying the collectionId in the address bar). Here the problem is that the state does not get the collectionId parameter. So can some please point how I can insert the default collectionId of the user when I am navigating to the state through URL routing.

Thanks,

1
  • Please see below answer for approval if it is useful. Commented Sep 22, 2016 at 14:44

1 Answer 1

2

Per the UI Router docs

In state controllers, the $stateParams object will only contain the params that were registered with that state. So you will not see params registered on other states, including ancestors.

The work around is to use resolve in the parent route, then inject the resolved value into the child state/controller:

$stateProvider
.state('home', {
  url: '/home',
  templateUrl: 'views/home.html',
  controller: 'HomeCtrl'
})
.state('home.books', {
  url: '/:collectionId',
  abstract: true,
  controller: 'BooksCtrl',
  resolve:{
      collectionId: ['$stateParams', function($stateParams){
          return $stateParams.collectionId;
      }]
  }
})
.state('home.books.displaybooks', {
  url: '^/books',
  templateUrl: 'views/displaybooks.html',
  // controller: 'DisplayBookCtrl' // this just needs collectionId now
  controller: function($stateParams, collectionId){
       console.log(collectionId);
  }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.