Search code examples
javascriptarrayspolymer

how to sort dom-repeat items in google-polymer


I have a problem in google-polymer when working with data-binding I need to sort dom-repeat items in the polymer . I need to write a function for sorting, and use it for all my dom-repeats

i cannot find a way.
this is my sort function:

 sort: function(a, b) {
          var nameA = a.name.toUpperCase();
          var nameB = b.name.toUpperCase(); 
          if (nameA < nameB) {
            return -1;
          }
          if (nameA > nameB) {
            return 1;
          }
          // names must be equal
          return 0;
        }

how i can do it?

Tnx


Solution

  • You can use sort property like this :

    <dom-module id="my-element">
      <template>
        <style>
        </style>
        <template is="dom-repeat" items="[[items]]" sort="sort">
          <div>{{item.name}} - {{item.age}}</div>
        </template>
      </template>
      <script>
        HTMLImports.whenReady(function() {
          Polymer({ 
            is: 'my-element',
            properties: {
              items: {
                type: Array,
                value: [
                  {name: "Saman", age: 20},
                  {name: "Mahdi", age: 20},
                  {name: "Erlik", age: 48}
                ]
              }
            },
            sort: function(a, b) {
              var nameA = a.name.toUpperCase(); 
              var nameB = b.name.toUpperCase(); 
              if (nameA < nameB) {
                return -1;
              }
              if (nameA > nameB) {
                return 1;
              }
    
              // names must be equal
              return 0;
            }
          });
        });
      </script>
    </dom-module>
    <my-element></my-element>
    

    Ref. https://www.polymer-project.org/2.0/docs/devguide/templates#filtering-and-sorting-lists