Search code examples
javascriptember.jshandlebars.js

How to use Ember query parameters with beforeModel and select?


Demo: http://jsbin.com/zexopa/1/edit?html,js,output

I use the query parameters in my application. And the queryParameters are 'name' and 'category'.

The 'name' parameter is used in the select and the 'category' uses the input, but there is something wrong with the select 'name' if I set it default to null.

If I change the 'name', the 'name' always is undefined in the url.

Route:

App.IndexRoute = Ember.Route.extend({
  beforeModel: function() {
    this.controllerFor('index').set('products', [1,2,3]);
  },
  model: function() {
    return [{'is_active':false, 'name':'One'}, {'is_active':false, 'name':'Two'}, {'is_active':false, 'name':'Three'}, {'is_active':false, 'name':'Four'},{'is_active':false, 'name':'Five'}];
  },
  actions: {
    queryParamsDidChange: function() {
      this.refresh();
    }
  }
});

Controller:

App.IndexController = Ember.Controller.extend({
  queryParams: ['name', 'category'],
  name: null,
  category: null
});

Template:

<script type="text/x-handlebars">
  <h2>Welcome to Ember.js</h2>

  {{outlet}}
</script>

<script type="text/x-handlebars" data-template-name="index">
  {{view "select" content=products value=name prompt="all"}}
  {{input type="text" value=category class="form-control"}}
  <ul>
    {{#each model as |item|}}
      <li>{{item.name}}</li>
    {{/each}}
  </ul>
</script>

Can you help to check what happens to my application?


Solution

  • Query params must be string to be properly binded. Your input works, as the value is String object. In name array you provided Integer. Unfortunately, I have not found any mention about that in docs, but you can see a working demo here: http://jsbin.com/lixili/1/edit?html,js,output

    If I can give you some tip about your code:

    • beforeModel is not a place for setting controller properties, do it in setupController method as in JSBin provided
    • You did not defined query params in route, but you could and get rid of the queryParamsDidChange

    Hope I helped!