Polymer 1.0 dom-repeat display index starting at 1
Asked Answered
C

1

6

I am using Polymer 1.0 to create a shopping/checkout cart. I have customers who may want to ship their order to multiple addresses. In the receipt, I need to list all the addresses with an index:

Address 1
John Doe
1234 Main St
...

Address 2
Jane Smith
999 Broadway
...

How do I get the index to start at 1 instead of 0?

    <template is="dom-repeat" items="{{shipping_details}}" as="address">
        <div>Address <span>{{index}}</span></div>
        <div>{{address.name}}</div>
        <div>{{address.line1}}</div>
    </template>

This is a simplification of my actual code, but the principle is the same. I have tried to make a js function that takes the index as a parameter and sets the innerHTML to index++, but I don't know what event it should fire on or how to get it to call the function.

    <div>Address <span on-some-event="displayIndex(index)"></span></div>

I am new to all of this, so you can't go in to too much detail about how to make this work. Thank you for your help in advance!

Coenocyte answered 13/7, 2015 at 15:58 Comment(0)
F
12

You can use a computed binding for this.

Instead of this:

<span on-some-event="displayIndex(index)"></span>

Do this:

<span>{{displayIndex(index)}}</span>

When displayIndex is this:

function (index) {
    return index + 1;
}

Note: displayIndex can be

  1. a method on the element prototype
<dom-module id="cart-addresses">
    <template is="dom-repeat" items="{{shipping_details}}" as="address">
        <div>Address <span>{{displayIndex(index)}}</span></div>
        <div>{{address.name}}</div>
        <div>{{address.line1}}</div>
    </template>
    <script>
        Polymer({
            is: 'cart-addresses',
            ...
            displayIndex: function(index) {
                return index + 1;
            }
            ...
        });
    </script>
</dom-module>
  1. a method attached to an auto-binding template
    <template is="dom-bind">
        ...             
        <template is="dom-repeat" items="{{shipping_details}}" as="address">
            <div>Address <span>{{displayIndex(index)}}</span></div>
            <div>{{address.name}}</div>
            <div>{{address.line1}}</div>
        </template>
    </template>
    <script>
        var template = document.querySelector('template[is="dom-bind"]');

        ...

        template.displayIndex = function (index) {
            return index + 1;
        };
    </script>
Finley answered 13/7, 2015 at 16:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.