使用repeat和in expression,迭代数组,但交换
是微不足道的 this.data = ["foo","bar"];
到
this.data = {foo:"football",bar:"barfly"}
无法迭代对象。我已经看到使用Object.key来获取每个值的示例,但返回的索引是0,1而不是“foo”“bar”。
虽然这个简单的例子不使用2路绑定,但我想继续支持它,以防我将来需要它。
http://jsbin.com/copogeyome/1/
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Polymer</title>
<script src="http://www.polymer-project.org/components/webcomponentsjs/webcomponents.js"></script>
<link rel="import" href="http://www.polymer-project.org/components/polymer/polymer.html">
</head>
<body>
<polymer-element name="an-consumer" attributes="data" noscript>
<template>testing {{data.foo}}<br>
<template id="foo">f {{}}<br></template>
<template id="bar">b {{}}<br></template>
<template id="0">0 {{}}<br></template>
<template id="1">1 {{}}<br></template>
<template id="2">2 {{}}<br></template>
{
<template repeat="{{obj,index in data}}" bind="{{data}}">
( {{index}} - {{obj}} ) = <template ref="{{index}}" bind="{{obj}}"></template>
</template>
}
</template>
</polymer-element>
<polymer-element name="an-supplier" attributes="data">
<template></template>
<script>
Polymer({
ready: function(){
this.data = ["foo","bar"];
//this.data = {foo:"football",bar:"barfly"}
}
});
</script>
</polymer-element>
<polymer-element name = "an-root" noscript>
<template>
<an-supplier data="{{stuff}}"></an-supplier>
<an-consumer data="{{stuff}}"></an-consumer>
</template>
</polymer-element>
<an-root>
</an-root>
</body>
</html>
答案 0 :(得分:3)
虽然没有内置的迭代对象的能力,但您可以使用 filter 轻松实现此功能:
<template repeat="{{key in data | getKeys}}">
<span>Key: {{key}}</span>
<span>Value: {{data[key]}}</span>
</template>
<script>
Polymer({
ready: function(){
// this.data = ["foo","bar"];
this.data = {foo:"football",bar:"barfly"}
}
// filter function to use in looping objects
getKeys : function(o) {
return Object.keys(o);
}
});
</script>
如果您有其他问题,请不要犹豫。