Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

javascript - Knockout : foreach data not display in HTML

I want to display multi dimentional ko observable array data in html. But, i didn't get output.

My code :

<!-- 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() is ko observable variable. customVal is ko observable array.

output of customVal is :

enter image description here

I want to display custom_option_select_text and display key name on first p tag.

How to do it ?

Expected Result :

enter image description here

please help me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 -->

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...