Router Map a Controller's Property to a Different Query Param Key



The controller has a default query parameter property which attaches a query parameter key to it and maps a controller property to a different query parameter key.

Syntax

Ember.Controller.extend ({
   queryParams: {
      queryParamName: "Values"
   },
   queryParamName: null
});

Example

The example given below shows mapping a controller's property to a different query param key. Create a new route and name it as parammapcontrol and open the router.js file to define 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('parammapcontrol');
});

//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>Map a Controller's Property</h2>
{{#link-to 'parammapcontrol'}}Click Here{{/link-to}}

When you click the above link, the page should open with an input box which takes a value entered by an user. Open the parammapcontrol.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 parammapcontrol.js file created under app/controllers/ with the following code −

import Ember from 'ember';

export default Ember.Controller.extend ({
   queryParams: [{
      
      //mapping the string 'querystring' of the 'query's' query parameter
      query: "querystring"
   }],
   
   //initialy query's 'query parameter' will be null
   query: null,
   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 Map Controllers Property

When you click on the link, it will generate an input box wherein you can enter a value. This will send an action to the addQuery method −

Ember.js Router Map Controllers Property

After clicking the button, it will show the parameter value to the right of the "?" in a URL −

Ember.js Router Map Controllers Property
emberjs_router.htm
Advertisements