Router Default Values and Deserialization



You can set the default value for the controller query parameter property the value of which will not be serialized into the URL.

Syntax

Ember.ArrayController.extend ({
   queryParams: 'queryParameterName',
   queryParameterName: defaultValue
});

Example

The example given below specifies setting the default value to the query parameter. Create a new route and name it as defaultvaluedeserialize and open the router.js file to define the URL mappings −

import Ember from 'ember';                   
//Access to Ember.js library as variable Ember
import config from './config/environment';
//It provides access to app's configuration data as variable config 

//The const declares read only variable
const Router = Ember.Router.extend ({
   location: config.locationType,
   rootURL: config.rootURL
});

//Defines URL mappings that takes parameter as an object to create the routes
Router.map(function() {
   this.route('defaultvaluedeserialize');
});

//It specifies Router variable available to other parts of the app
export default Router;

Open the file application.hbs file created under app/templates/ with the following code −

<h2>Default Values and Deserialization</h2>
{{#link-to 'defaultvaluedeserialize'}}Click Here{{/link-to}}

When you click the above link, the page should open with a input box which takes a value entered by the user. Open the defaultvaluedeserialize.hbs file and add the following code −

//sending action to the addQuery method
<form {{action "addQuery" on = "submit"}}>
   {{input value = queryParam}}
   <input type = "submit" value = "Send Value"/>
</form>
{{outlet}}

Now open the defaultvaluedeserialize.js file created under app/controllers/ with the following code −

import Ember from 'ember';

export default Ember.Controller.extend ({
   //assigning query parameter name as 'query'
   queryParams: 'query',
   //assigning the query param to a default value as 1
   query: 1,
   queryParam: Ember.computed.oneWay('query'),
   actions: {
      
      addQuery: function () {
         this.set('query', this.get('queryParam'));
         document.write(this.get('query'));
      }
   }
});

Output

Run the ember server and you will receive the following output −

Ember.js Router Default values and deserialization

When you click on the link, it displays the specified default value in the input box −

Ember.js Router Default values and deserialization

After clicking the button, it will show the default value and it won't be serialized into the URL −

Ember.js Router Default values and deserialization
emberjs_router.htm
Advertisements