我有以下对象:
var Transaction = function (data) {
this.ID = ko.observable(data.transaction.ID);
this.number = ko.observable(data.transaction.number);
this.userID = ko.observable(data.transaction.userID);
this.password = ko.observable(data.transaction.password);
this.Properties = ko.observableArray(data.Property);
}
属性可观察数组如下所示(在JSON中):
[{"address1":"111 Broadway","city":"Brooklyn","state":"NY","zip":null},
{"address1":"222 Broadway","city":"Brooklyn","state":"NY","zip":null}]
在我的HTML中,我有类似以下内容:
<span>PROPERTY</span>
<span data-bind="foreach: Properties">
<span data-bind="text: address1"></span>
<span data-bind="text: city"></span>
span data-bind="text: state"></span>
<span data-bind="text: zip"></span>
</span>
在浏览器中看起来像:
PROPERTY
111 Broadway
Brooklyn
NY
222 Broadway
Brooklyn
NY
我希望它看起来像:
111 Broadway, Brooklyn, NY
222 Broadway, Brooklyn, NY
有什么建议吗?
最佳答案
您可以在Transaction
原型中作为Properties
列表视图创建一个计算属性,这将简化与之关联的HTML标记。
this.propertyView = ko.pureComputed(function() {
return this.Properties().map(function(prop) {
var singleProp = '';
for (var p in prop)
if (prop[p])
singleProp += prop[p] + ', ';
return singleProp.slice(0,-2);
});
}, this);
<span>PROPERTIES</span>
<!-- ko foreach: propertyView -->
<p data-bind="text: $data"></p>
<!-- /ko -->