Bind JSON key value pairs to table template in polymer dart

烂漫一生 提交于 2019-12-13 16:25:54

问题


how I can bind to the key/value pairs within a json object in polymer notation. i have template repeat="{{objects in jsonarray}}"... I want to lay out a table. say each object has {1: one, 2: two, 3: three}

something like:

<template repeat="{{item in mylist}}">
  <tr>
     <template repeat="{{key, value in item}}">
        <td>{{key}}: {{value}}</td>
     </template>
  </tr>
</template>

回答1:


this code works for me:

Dart:

@observable List jsonlist = toObservable(JSON.decode('[{"1":"one"},{"2":"two"}]'));

HTML:

<template repeat="{{ foo in jsonlist }}">
  {{ foo }}
  <template repeat="{{ key in foo.keys }}">
    {{ key }} = {{ foo[key] }}
  </template>
</template>

With this code I get the following output:

{1: one} 1 = one {2: two} 2 = two

Regards Robert




回答2:


I think it should work this way:

<template repeat="{{item in mylist}}">
  <tr>
     <template repeat="{{key in item.keys}}">
        <td>{{key}}: {{item[key]}}</td>
     </template>
  </tr>
</template>

Please try and add a comment when it doesn't work (so I get a notification) then I build a demo app and try it myself.




回答3:


I managed to get this working the way I wanted, which was to output a JSON array of JSON objects to a table, like this:

jsontable.dart

import 'package:polymer/polymer.dart';
import 'dart:html';
import 'dart:convert';

@CustomTag('json-table')
class jsontable extends PolymerElement {

   @observable List jsonarray = [{"id":1,"description":"cat"},{"id":2,"description":"dog"}, {"id":3,"description":"fairy"}];

   jsontable.created() : super.created() {}
}

jsontable.html

<polymer-element name="json-table">
  <template>
    <div>
      <table border="1">
        <tbody>
          <thead>
            <tr>
              <template repeat="{{ key in jsonarray.first.keys }}">
                <th>{{key}}</th>
              </template>
            </tr>
          </thead>
          <template repeat="{{ jsonobject in jsonarray }}">
            <tr>
                <template repeat="{{ value in jsonobject.values }}">
                  <td>{{value}}</td>
                </template>
            </tr>
          </template>
        </tbody>
      </table>
    </div>
  </template>
  <script type="application/dart;component=1" src="jsontable.dart"></script>
</polymer-element>


来源:https://stackoverflow.com/questions/23450520/bind-json-key-value-pairs-to-table-template-in-polymer-dart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!