Search code examples
ember.jsember-data

Ember queryParams in Route VS in Controller


I am confused about queryParams from Ember's documentation. It shows that you can put queryParams to Controller or Route. What are the differences having queryParams in Route vs Controller except syntax?

As far as I understand, having queryParams as object in Route allows me to do following things:

  1. Use replace: true and refreshModel options.
  2. Capture queryParams faster than controller.
  3. Model hook can receive params values

In what case would you choose to have queryParams in Controller?


Solution

  • You can use the controller to set default values for queryParams, bind queryParam values to values in your template, and update queryParam values. When these values change in the controller, the controller updates the url, and the route takes the url values so that you can then make ember-data requests.

    Let's say you're rendering a paginated list of items, with pagination controls on the page. On the initial page load, you load the first page of results from the API. In order to link up that 'next page' action to load the next set of results, you need to use the controller to update the queryParams.

    Your route might look like this:

     export default Route.extend({
      queryParams: {
        pageNumber: {
          refreshModel: true //when we set this to true, every time the pageNumber param changes, the model hook below will refresh and the data set will update.
        }
      },
    
      model(params) {
       return this.get('store').query('items', params);
      }
    
     });
    

    And your controller might look like this:

    export default Controller.extend({
      queryParams: ['pageNumber'],
      pageNumber: 1,
    
      actions: {
        nextPage () {
          const newPageNumber = this.get('pageNumber') + 1;
          this.set('pageNumber', newPageNumber);
        }
      }
    });
    

    When you update the pageNumber attribute in your controller, this will bind to the route and refresh the model, loading the next page of data.

    Essentially the controller is there if you need to modify any queryParams from your template. You might have a list of data that can be filtered, paged, updated etc., and you can control these parameters using the controller.

    You can also set default values for params in the controller.

    Hope this is helpful! (: