简体   繁体   中英

Knockout will not generate a dropdown from an objects array property when foreach over an array of objects

I have a form that generates an array of attribute objects. The attribute objects have an array property that is an array of attribute values. The form allows you to add an attribute name and an array of attribute values and maps to an attribute object:

function Attribute(data) {
      var self = this;
      self.Name = ko.observable([data.attributeName]);
      self.Values = ko.observable([data.attributeValues]);
  }

And the Values array is an attribute of AttributeValues:

  function AttributeValue(data) {
      this.Value = data.value;
  };

With the ViewModel having an array of AttributeValues as you create them, and will pass it with the name of the Attribute to its local array of Attributes

   function newProductViewModel() {
      var self = this;
      self.attributeName = ko.observable();
      self.attributes = ko.observableArray([]);
      self.attributeValues = ko.observableArray([]);

When you are creating an attribute in the form, knockout has no problem listing the attribute values you have added to the array of AttributeValues:

   <select multiple="multiple" height="5" data-bind="options: attributeValues, optionsText: 'Value', selectedOptions: selectedItems, optionsCaption: 'Added Values...'">

where attributeValues is the ViewModel's array of attributeValues.

Once an attribute name and a list of attribute values has been added, and you add the Attribute, I foreach over the observableArray attributes property on the ViewModel to show a list of the added Attributes as you create them.

The Problem

The problem is I am showing a drop down (select) for each attribute's array of attribute Values Values :

<ul data-bind="foreach: attributes">
   <li>
    <div>
       <span data-bind="text: Name"></span>
       <select multiple="multiple" height="5" data-bind="options: Values, optionsText: 'Value', selectedOptions: selectedItems, optionsCaption: 'Added Values...'">

     .....remove for sake of brevity

But it won't list the Value for each AttributeValue in the Values array for each Attribute

I have stepped through and can see that the Values property does get set with the proper values.

What am I doing wrong?

I figured out the problem. I was passing in an array "attributeValues" to the Attribute object and putting it in array

self.Values = ko.observable([data.attributeValues]);

So I assume it would be an array of one element with the array of attributeValues in that index. When stepping through and I seen the correct number of elements because I was only adding one value, but actually looking at the array within the first index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM