3

I can't seem to understand how to do the following looking over the docs for "ember power select".

I have a model user:

export default Model.extend({
    "state": attr('string')
});

Stored as a value in the DB is: NY for state

I also have the following data to load into the ember power select options:

stateList: [
    {
        label: 'New Jersey',
        value: 'NJ'
    },
    {
        label: 'New York',
        value: 'NY'
    },
]

The following handlebar code will load in the states and display them. You can search and select the state:

{{#power-select 
    options=stateList
    searchField="label"
    selected=state
    onchange=(action (mut state))
    as |state|
}}
    {{state.label}}
{{/power-select}}

The issue... on select of 'New York', I would like the stored value of 'state' to be 'NY'

Right now it's simply storing the entire object. I understand through 'onchange' I can set the value, but I don't really understand how you set the value to 'NY' and have it selected?

I've tried doing

this.set('state',selection.value)

But I think it's looking for the index of the object, I however simply want to pass 'NY' and not a whole object... is this possible?

glaucon
  • 8,112
  • 9
  • 41
  • 63
Matt
  • 1,811
  • 1
  • 19
  • 30

1 Answers1

3

Answer to your question is NO(AFAIK). But you can achieve this using computed property.

Component js code

import Ember from 'ember';

export default Ember.Component.extend({
  stateList: [{'label': 'New Jersey','value': 'NJ'},{ 'label': 'New York','value': 'NY'}],
  state:'NY',
  selectedState: Ember.computed('state', function(){    
    return this.get('stateList').findBy('value',this.get('state'));
  }),

  actions:{
    setSelectedState(selectedVal){      
      this.set('state',selectedVal.value);
    }
  }
});

Component hbs code

{{#power-select 
    options=stateList
    searchField="label"
    selected=selectedState
    onchange=(action 'setSelectedState')
    as |state|
}}
    {{state.label}}
{{/power-select}}
{{yield}}

Here is Ember-Twiddle

Ember Freak
  • 12,918
  • 4
  • 24
  • 54
  • The Twiddle does only allow to select an entry once, changing the value doesn't seem possible. Do you have an idea how this could be fixed? – Harald Gliebe Sep 07 '17 at 08:19
  • 1
    Here is the updated [twiddle link](https://ember-twiddle.com/8894d46f8bca43dfdf42025a1c847aa4?openFiles=templates.application.hbs%2Ctemplates.components.selected-test.hbs). we need to include `
    ` dummy div in application.hbs for ember wormhole addon to place dropdown correclty.
    – Ember Freak Sep 07 '17 at 11:47