Souvik Basu
Souvik Basu

Reputation: 3139

Polymer: How to repeat dropdown items

I am using Polymer paper-dropdown-menu.

I need to show drop down for numbers 1 to 5. The crude way to do it is

<paper-dropdown-menu label="Numbers" >
  <paper-dropdown class="dropdown">
    <core-menu class="menu">
        <paper-item>1</paper-item>
        <paper-item>2</paper-item>
        <paper-item>3</paper-item>
        <paper-item>4</paper-item>
        <paper-item>5</paper-item>
    </core-menu>
</paper-dropdown>

Is there a way to avoid repeating <paper-item> code by using <template> Something like:

   <template repeat="{{ i in [0:25] }}">
       <paper-item>i</paper-item>
   </template>

Upvotes: 0

Views: 771

Answers (2)

jimi dough10
jimi dough10

Reputation: 2016

you could do a "range" function to produce the array then use the array in the method already posted.

that would look something like

<paper-dropdown-menu label="Numbers" >
  <paper-dropdown class="dropdown">
    <core-menu class="menu">
      <template repeat="{{range}}">
        <paper-item>{{}}</paper-item>
      </template>
    </core-menu>
  </paper-dropdown>
</paper-dropdown-menu>

then in js you create the range function

var range = function(begin, end) {
  if (typeof end === "undefined") {
    end = begin; begin = 0;
  }
  var result = [], modifier = end > begin ? 1 : -1;
  for ( var i = 0; i <= Math.abs(end - begin); i++ ) {
    result.push(begin + i * modifier);
  }
  return result;
}

this range function came from this post which also has several diff methods for doing this. Does JavaScript have a method like "range()" to generate an array based on supplied bounds?

then you assign the range to the polymer variable the repeat template is using

this.range = range(1,25);

hope this helps. sorry i couldn't answer yesterday was leaving for work when i sent last response.

edit: a example on plunker http://plnkr.co/edit/4TkQdR2B5vakbwOSAulK?p=preview

Upvotes: 1

Kristjan Liiva
Kristjan Liiva

Reputation: 9579

As mentioned in the comments there is an example in the demo provided by polymer. https://github.com/Polymer/paper-dropdown/blob/master/demo.html

<x-trigger icon="menu">
  <paper-dropdown class="with-margin">
    with margin<br>
    <br>
    <template repeat="{{countries}}">
      {{name}}<br>
    </template>
  </paper-dropdown>
</x-trigger>


scope.countries = [
  {name: 'Afghanistan', code: 'AF'},
  {name: 'Åland Islands', code: 'AX'}
];

Upvotes: 1

Related Questions