wuxiekeji
wuxiekeji

Reputation: 1902

How do I push data to a Polymer dom-repeat template?

Say I have the following code, which is a collection of cards with titles and text:

<template id="cardSetFoo" is="dom-bind">
  <template id="cardSet" is="dom-repeat" items="[[data]]">
    <paper-card>
      <div class="card-body">
        <h4>[[item.title]]</h4>
        [[item.text]]
      </div>
    </paper-card>
  </template>
</template>

And I want to populate the set of cards:

document.querySelector('#cardSet').push('data',[{'title':'Title','text':'Description'}]);

I keep getting Uncaught TypeError: Cannot read property 'length' of undefined(…) (notify-path.html:476)

Can anyone enlighten me on how to populate a dom-repeat template? Thanks!

Upvotes: 0

Views: 676

Answers (1)

Srik
Srik

Reputation: 2381

Try this

var app = document.querySelector('#cardSetFoo');
if (!app.data) {
  app.data = [];
}
app.push('data', [{'title':'Title','text':'Description'}]);

Your dom-repeat code is incorrect. You have to use item to access array items inside the dom-repeat. You can use as attribute to give it a different name as below

<template id="cardSetFoo" is="dom-bind">
  <template id="cardSet" is="dom-repeat" items="[[data]]" as="card">
    <paper-card>
      <div class="card-body">
        <h4>[[card.title]]</h4>
        [[card.text]]
      </div>
    </paper-card>
  </template>
</template>

Upvotes: 3

Related Questions