0

I have an array which just have values in following format:

var myArray = [ "Value1", "V1lue2" ,"Value3","a1lue4"  ]

Now I want to loop through them and add them to UL like below:

<ul data-bind="foreach:myArray">
    <li>
        <span data-bind="text: $value"> </span>:
    </li>
</ul>

I checked knockout documentation which have examples with name value JSON , but not from direct array.

Example:

<ul data-bind="foreach: people">
    <li>
        Name at position <span data-bind="text: $index"> </span>:
        <span data-bind="text: name"> </span>
        <a href="#" data-bind="click: $parent.removePerson">Remove</a>
    </li>
</ul>

How do I loop through myArray and apply binding to current UL?

Simsons
  • 12,295
  • 42
  • 153
  • 269

1 Answers1

1

You just need to change $value to $data - which is a contextual variable that represents the current item in the array:

<span data-bind="text: $data"> </span>:

Here's a working snippet:

var model = function() {
  var self = this;
  self.myArray = ["Value1", "V1lue2", "Value3", "a1lue4"];
};

ko.applyBindings(new model());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<ul data-bind="foreach: myArray">
  <li>
    <span data-bind="text: $data"> </span>:
  </li>
</ul>
Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55