Squis
Squis

Reputation: 931

Using Polymer iron-ajax in repeating template

How do I load a json file and use the data in a repeating template? This code doesn't produce anything:

<dom-module id="name-list">
    <template>
        <iron-ajax auto url="names.json" handleAs="json" lastResponse="{{data}}"></iron-ajax>
        <template is="dom-repeat" items="{{data}}">
            <div>First name: <span>{{item.firstName}}</span></div>
            <div>Last name: <span>{{item.lastName}}</span></div>
        </template>
    </template>
</dom-module>

<script>
    Polymer({
        is: "name-list"
    });
</script>

Here's my json file (Edit: corrected after vasek's reply):

{
    [
        {
            "firstName": "John",
            "lastName": "Smith"
        },{
            "firstName": "Jane",
            "lastName": "Doe"
        }
    ]
}

I'd like to have the following:

<div>First name: <span>John</span></div>
<div>Last name: <span>Smith</span></div>
<div>First name: <span>Jane</span></div>
<div>Last name: <span>Doe</span></div>

I'm including iron-ajax elsewhere in my code. I've already tested the general functionality. It works, just not in the context of data-binding.

Upvotes: 3

Views: 2580

Answers (3)

TheSPD
TheSPD

Reputation: 177

I was also stuck with a similar code, unfortunately the above answers didn't solve the issue for me. However, when I put the <iron-ajax> element after the <template is="dom-repeat">, it worked for me.

Upvotes: 1

Ben Thomas
Ben Thomas

Reputation: 3200

Firstly as vasek says, your JSON is incorrect. dom-repeat needs an array to iterate over and your JSON is currently returning an object. Secondly, you are accessing the properties on the iron-ajax element incorrectly. As the docs state

In order to configure camel-case properties of elements using attributes, dash- case should be used in the attribute name.

You are trying to set handleAs and lastResponse. In order to do these you need to change them to the dash-case:

<iron-ajax auto url="names.json" handle-as="json" last-response="{{data}}"></iron-ajax>

Otherwise, everything else should work correctly.

Upvotes: 4

vasek
vasek

Reputation: 341

Your json file is in wrong format. It should be like this:

    [
        {
            "firstName": "John",
            "lastName": "Smith"
        },
        {
            "firstName": "Jane",
            "lastName": "Doe"
        }
    ]

Upvotes: 1

Related Questions