5
votes

So I'm trying to dynamically generate a paper-dropdown-menu populated from an AJAX data source, which is working great using the code below:

<polymer-element name="my-element" attributes="selected">
  <template>

    <core-ajax auto url="/api/items/" response="{{items}}" handleAs="json"></core-ajax>
    <paper-dropdown-menu selected="{{selected}}">
      <template repeat="{{items}}">
        <paper-item name="{{id}}" label="{{name}}"></paper-item>
      </template>
    </paper-dropdown-menu>

  </template>

But if I set the initial selected item to be either the value of the published attribute, or a value that I set in the 'ready' callback, the dropdown menu item does not get selected when the items are loaded:

  <script>
  Polymer({
    publish: {
      selected: null
    }
  });
  </script>
</polymer-element>

I understand that this is happening because the 'selected' property is being set before the template in the dropdown gets bound, but my question is whether there is a way to either 1) defer the 'selected' property change until after the template is bound or 2) otherwise reliably set an initially selected value for the dropdown menu?

2
Have you tried defining itemsChanged() and setting it in that? - ebidel
Yes, however this does not work when I try setting the selected property to an initial value from outside the element. Sorry for the confusion, I've edited the question to reflect that constraint. - Christopher R

2 Answers

4
votes

One option would be to not render the dropdown until the data is available.

ex: http://jsbin.com/piyogo/13/edit

<polymer-element name="foo-drop">
  <template>
    <core-ajax auto
               url="http://www.json-generator.com/api/json/get/bJMeMASvTm?indent=2"
               response="{{items}}"    
               handleas="json">
    </core-ajax>
    <template if="{{items}}">
      <paper-dropdown-menu selected="{{selected}}">
        <template repeat="{{item in items}}">
          <paper-item label="{{item.name}}"></paper-item>
        </template>
      </paper-dropdown-menu>  
    </template>
  </template>  
  <script>
    Polymer({
      publish: {
        selected: null
      }
    });
  </script>
</polymer-element>

<foo-drop selected="2"></foo-drop>
3
votes

For Polymer 1.0 (and later), the same can be achieved with the following code:

<iron-ajax auto url={{url}} handle-as="json" last-response="{{items}}"></iron-ajax>

<template is="dom-if" if="{{items}}">
  <paper-dropdown-menu-light label="[[label]]" no-animations selected-item="{{selected}}">
    <paper-listbox class="dropdown-content">
      <template is="dom-repeat" items="[[items]]">
        <paper-item>[[item.name]]</paper-item>
      </template>
    </paper-listbox>
  </paper-dropdown-menu-light>  
</template>