简体   繁体   中英

dynamic params for ember component

I'm working on an Ember project in which I have to specify the parameters of the component dynamically.

I have the following array in the .js controller:

componentParams: ["id", "name"]

What I want to do is to take the values in the array and use them in handlebars as the component parameter like this

{{component-name id=somevalue name="somevalue"}}

Could this be done?

An approach I use.

controller.js

navbarParams: {
   titleToShow: 'General.ResearchProjects',
   glyphicon: 'glyphicon glyphicon-globe',
   infoText: 'information/project'
},

template.hbs

{{my-navbar params=navbarParams}}

my-navbar.hbs

<h1> {{params.titleToShow}} <span class={{params.glyphicon}}> </span> </h1>

If your parameters are queryParams

They should be defined like that

queryParams: ['foo', 'bar',],
foo: null,
bar: null

{{my-navbar first=foo second=bar}}

Honestly it depends, if you are stuck with that array - you can use computed properties to extract the proper array values. ( This is probably not recommended - a better approach would be to format your componentParams into an object ( like @kristjan's example).

If you are stuck with the array - and the positions will never change ( id will always be componentParams[0] & name will always be componentParams[1] , you could try something like this ::

// controller
import Ember from 'ember';

const {
  Controller,
  computed,
  get
} = Ember;

export default Controller.extend({
  componentParams: ['id', 'name'],
    componentName: computed('componentParams', {
    get() {
        return get(this, 'componentParams')[1];
    }
  }),
  componentId: computed('componentParams', {
    get() {
        return get(this, 'componentParams')[0]; 
    }
  })
});


// template
{{my-component name=componentName id=componentId}}

// component/template
name:: {{name}}
<br>
id :: {{id}}

check out this twiddle for a working example

Does this help ??

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM