Ember.js: select state not saved in URL when reload page

75 views Asked by At

There are select on the page for choosing country and it's need to save selected value in URL. I declared query params in route-driven controllers. It's all work! If country select is changed then url also changed.

Demo: http://output.jsbin.com/releza

But if I reload page with some valid GET params then it params convert to 'undefined'. For example, I try to load page

http://output.jsbin.com/releza#/?country=2

and it redirect to

http://output.jsbin.com/releza#/?country=undefined

Why?

# index.hbl
<script type="text/x-handlebars" id="index">
    {{view "select" content=countries   
                  optionValuePath="content.id" 
                  optionLabelPath="content.name"  
                  value=country
                  prompt="Select a country"}}
</script>

# apps.js
App = Ember.Application.create({});

// ROUTES
App.IndexRoute = Ember.Route.extend({
  setupController: function(controller, model) {
    controller.set('countries', this.store.find('country'));
    }
});

// CONTROLLERS
App.IndexController = Ember.Controller.extend({
    queryParams: ['country'],
    country: null,
});

// MODELS
App.Country = DS.Model.extend({  
    name: DS.attr('string'),
});

$.mockjax({
  url: "/countries",
  dataType: 'json',
  responseText: {
    "country": [
      {"id":1, "name":"Абхазия"},
      {"id":2, "name":"Австралия"},
      {"id":3, "name":"Австрия"},
      {"id":4,"name":"Азейбарджан"},
    ],
  }
});
1

There are 1 answers

4
Andrey Mikhaylov - lolmaus On BEST ANSWER

You're using setupController to feed data into the controller. And you set the counties property to a promise returned by store.find().

When the page loads, Ember does not wait for that promise to resolve. Thus, the select box appears with no entries, and the query params entry is considered non-existing and replaced by undefined.

To resolve the issue, use the route's model hook. Then Ember will wait for the promise to resolve before passing the word to the controller, and the select box will appear with its items preloaded.

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

Note that you're not experiencing the issue from your previous question because Ember Data internally converts record ids to strings.