问题描述
我想在html中显示多维的可观察数组数据.但是,我没有得到输出.
I want to display multi dimentional ko observable array data in html. But, i didn't get output.
我的代码:
<!-- ko if: ($parent.cust_opt_avail() === 1) -->
<!-- ko foreach: $parent.customVal() -->
<div class="product-custom-option-select">
<p class="options-label" data-bind="text:key"></p>
<p class="options-label" data-bind="text:custom_option_select_text"></p>
</div>
<!-- /ko -->
<!-- /ko -->
cust_opt_avail()是可观察的变量. customVal 是可观察的数组.
cust_opt_avail() is ko observable variable.customVal is ko observable array.
customVal的输出是:
output of customVal is :
我想在第一个p标签上显示 custom_option_select_text 并显示键名称.
I want to display custom_option_select_text and display key name on first p tag.
该怎么做?
预期结果:
请帮助我.
推荐答案
来自您的上一个问题和对此问题的评论,我收集您正在将对象设置为ko.observableArray()
.这是不正确的.您应该将customVal
设置为ko.observable()
.然后使用 Object.keys()
并使用foreach绑定中>别名.
From your previous question and comments in this question, I gather you're setting an object to ko.observableArray()
. This is not correct. You should set a customVal
to a ko.observable()
. Then use Object.keys()
and use aliasing in your foreach
binding.
var viewmodel = function() {
var self = this;
self.cust_opt_avail = ko.observable(1);
let customVal = {
Color: [{'custom_option_select_text': 'Red + $200.00'},
{'custom_option_select_text': 'Green + $250.00'}],
Size: {'custom_option_select_text': 'XL + $150.00'}
};
// This should be an observable
self.customVal = ko.observable(customVal);
};
ko.applyBindings(new viewmodel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<!-- ko if: (cust_opt_avail() === 1) -->
<div data-bind="foreach: { data: Object.keys(customVal()), as: 'key' }">
<div class="product-custom-option-select">
<p style="font-weight:bold" data-bind="text:key"></p>
<!-- ko if: Array.isArray($parent.customVal()[key]) -->
<!-- ko foreach: $parent.customVal()[key] -->
<p class="options-label" data-bind="text:custom_option_select_text"></p>
<!-- /ko -->
<!-- /ko -->
<!-- ko if: !Array.isArray($parent.customVal()[key]) -->
<p class="options-label"
data-bind="text:$parent.customVal()[key].custom_option_select_text"></p>
<!-- /ko -->
</div>
</div>
<!-- /ko -->
注意:
由于customVal
处于嵌套上下文中,因此您可能必须在所有内部绑定中添加另一个$parent
前缀.
Since customVal
is in a nested context, you might have to add another $parent
prefix to all the inner bindings.
这篇关于淘汰赛:foreach数据未显示在HTML中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!