Getting query params and segment values from parent route

Imagine a simple app that shows a menu, and list different results on the side when an option is clicked. Let’s say I structure the routes like this:

Router.map(function() {
  this.resource('items', function() {
    this.route('list', { path: '/:status' });
  });
});

It’s quite easy to get the dynamic segment and query params values on the ItemsListController, and ItemsListRoute, as described on the Ember docs.

However, what if I want to get the segment or query params values from the items controller?. Is it possible to do this, or should I structure the routes differently to achieve it?

It’s quite easy to get the dynamic segment and query params values on the ItemsListController, and ItemsListRoute, as described on the Ember docs.

From within your ItemController you can access the parent controller via this.parentController. And then you can use whatever strategy you have for reading the queryParams off the controller. I assume it would be as simple as:

this.parentController.getProperties(this.parentController.queryParams);

Thanks @jasonmit! , but I’m not completely sure if I get what you said. On this case is the opposite, I cannot get the values on the child route from its parent. I’m linking to the route like this:

/ linking from a menu in items template to the list route
link-to 'items.list' 'used' (query-params page=1)
  | Used Items

So I don’t understand how this.parentController.getProperties would work. Should the routes remain the same to work?

Or, should I use a single route and render the ItemsListController inside the Items template to get the params as you mentioned?

Thanks again!

I thought you were having issues around the use of an ArrayController. Could you fiddle your example using Ember Latest - JSFiddle - Code Playground and I’ll see what I can do to get it to work?

@jasonmit Sure. Here’s the feedle.

You can now access the params of parent routes in the transition that is an optional second param of the model hook:

model(params, transition)

For instance in your route:grandparent.parent.child you can get parent param like so:

transition.params["grandparent.parent"].my_param

You can also use the paramsFor method as well, which you can pass a route name to as the argument.

2 Likes

What about from a controller or component

For people coming back, this appears to no longer be the case. Here’s the newer API:

  model(params, transition) {
    const {
      intent: {
        queryParams,
      },
    } = transition;
}

EDIT:

I would use this method instead: Route - 3.10 - Ember API Documentation

  model(params) {
    const { id } = params;
    const { search } = this.paramsFor('map-feature');

    return {
      id,
      search,
    };
  }

It seems to preserve the typecasting of query params as well.

1 Like