Router Specifying Query Parameters



You can specify the query parameters on the route-driven controllers which can bind in the URL and configure the query parameters by declaring them on controller to make them active. You can display the template by defining a computed property of query parameterfilter of an array.

Syntax

Ember.Controller.extend ({
   queryParams: ['queryParameter'],
   queryParameter: null
});

Example

The example given below shows specifying query parameters on route-driven controllers. Create a new route and name it as specifyquery 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('specifyquery');
});

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

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

<h2>Specifying Query Parameters</h2>
{{#link-to 'specifyquery'}}Click Here{{/link-to}}

When you click on the above link, the page should open with a form. Open the specifyquery.hbs file to send the parameters on the route-driven controllers −

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

Now define the computed property of queryParam filtered array which will display the specifyquery template −

import Ember from 'ember';

export default Ember.Controller.extend ({
   //specifying the 'query' as one of controller's query parameter
   queryParams: ['query'],
   
   //initialize the query value
   query: null,
   
   //defining a computed property queryParam
   queryParam: Ember.computed.oneWay('query'),
   actions: {
      addQuery: function () {
         
         //setting up the query parameters and displaying it
         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 Query Parameters

When you click on the link, it will provide an input box to enter a value and sends an action to the addQuery method −

Ember.js Router Query Parameters

After clicking the button, it shows the key value pairs to the right of the ? in a URL −

Ember.js Router Query Parameters
emberjs_router.htm
Advertisements