聚合物1.0 dom-repeat显示索引从1开始

bjs*_*eld 7 javascript data-binding html5 polymer-1.0

我正在使用Polymer 1.0来创建购物/结账购物车.我的客户可能希望将订单发送到多个地址.在收据中,我需要列出所有带索引的地址:

地址1
John Doe
1234 Main St
...

地址2
Jane Smith
999 Broadway
...

如何让索引从1开始而不是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>
Run Code Online (Sandbox Code Playgroud)

这是我实际代码的简化,但原理是一样的.我试图创建一个js函数,它将索引作为参数并将innerHTML设置为index ++,但我不知道它应该触发什么事件或者如何让它调用函数.

    <div>Address <span on-some-event="displayIndex(index)"></span></div>
Run Code Online (Sandbox Code Playgroud)

我是所有这一切的新手,所以你不能详细介绍如何使这项工作.提前谢谢你的帮助!

cod*_*fin 12

您可以使用计算绑定.

而不是这个:

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

这样做:

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

如果displayIndex是这样的:

function (index) {
    return index + 1;
}
Run Code Online (Sandbox Code Playgroud)

注意: displayIndex可以

  1. 关于元素原型的方法
<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>
Run Code Online (Sandbox Code Playgroud)
  1. 附加到自动绑定模板的方法
    <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>
Run Code Online (Sandbox Code Playgroud)