I tried setting the initial value to null, but it didn't always work: sometimes my query parameter would appear in the URL, and sometimes it wouldn't. I solved this by manipulating browser history via window.history.replaceState(), if the query parameter wasn't in the URL. I put the code in my setter in Ember.run.schedule('afterRender', this, function() {...}) so that my logic runs after Ember is done rendering.
export default Ember.Controller.extend({
setMyParam: function(newValue) {
if (newValue !== null && typeof(newValue) !== 'undefined') {
Ember.set(this, 'myParam', newValue);
Ember.run.schedule('afterRender', this, function() {
window.location.toString().match(/^(.+?)(\?.+)$/); // $1 = base URL, $2 = query params
var queryParams = RegExp.$2;
if (queryParams) {
if (queryParams.indexOf('myParam') === -1) {
console.log('No myParam in query parameters. Setting myParam=' + newValue);
window.history.replaceState({}, document.title, window.location.toString() + '&myParam=' + newValue);
}
} else {
// No query parameters, so add it as the first query parameter
console.log('No query parameters, so adding myParam=' + newValue + ' as the first query parameter.');
window.history.replaceState({}, document.title, window.location.toString() + '?myParam=' + newValue);
}
});
} else {
console.log('setMyParam: newValue=' + newValue + ' is null or undefined. Not setting it!');
}
}
});