Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Polymer 1.0 dom-repeat should display index starting at 1 with HTML
Polymer.js is a JavaScript library created by Google that allows reusing HTML elements for building applications with components. When using dom-repeat in Polymer 1.0, the index starts at 0 by default, but you can display it starting from 1.
The Problem
By default, dom-repeat provides a zero-based index. If you want to display numbers starting from 1 (like a numbered list), you need to add 1 to the index value.
Solution: Using a Helper Function
Create a helper function that adds 1 to the index:
displayIndex: function(index) {
return index + 1;
}
Example Implementation
Here's a complete example showing how to display index starting at 1:
<dom-module id="my-element">
<template>
<template is="dom-repeat" items="[[subjects]]">
<div>Subject <span>[[displayIndex(index)]]</span>: [[item.name]]</div>
</template>
</template>
<script>
Polymer({
is: 'my-element',
properties: {
subjects: {
type: Array,
value: function() {
return [
{name: 'Math'},
{name: 'Science'},
{name: 'History'}
];
}
}
},
displayIndex: function(index) {
return index + 1;
}
});
</script>
</dom-module>
Output
Subject 1: Math Subject 2: Science Subject 3: History
Alternative: Inline Expression
You can also use an inline expression directly in the template:
<template is="dom-repeat" items="[[subjects]]">
<div>Subject <span>[[_computeDisplayIndex(index)]]</span>: [[item.name]]</div>
</template>
Conclusion
To display dom-repeat index starting at 1, create a helper function that adds 1 to the zero-based index. This approach keeps your template clean and logic reusable.
