0
votes

Hi I'm trying to do a foreach using a observableArray and I'm getting no result.

Where as in javascript file while debugging the data is getting loaded with the array. The html code is given below:

<!-- ko foreach: currencyarr -->
    <option data-bind="value:id, text:label"></option>
<!-- /ko -->

And the JSON file content is as follows:

"name" : "shuvagho",
"curarr" : [
            {"id": "inr", "label": "INR"},
            {"id": "usd", "label": "USD"},
            {"id": "aud", "label": "AUD"},
            {"id": "sgd", "label": "SGD"}
]

And the javascript code using knockout js is as follows:

self.currencyarr = ko.observableArray();
self.currencyarr(data.curarr);
1

1 Answers

2
votes

You forgot to use $data inside the foreach.

  var ViewModel = function(){
      var self = this;
      self.currencyarr = ko.observableArray();
      self.currencyarr(data.curarr);  
    }
    var data = {
    "name" : "shuvagho",
    "curarr" : [
                {"id": "inr", "label": "INR"},
                {"id": "usd", "label": "USD"},
                {"id": "aud", "label": "AUD"},
                {"id": "sgd", "label": "SGD"}
    ]};

    var viewModel = new ViewModel();

            ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<select>
<!--ko foreach: currencyarr-->
  <option data-bind="text:$data.label, value:$data.id" ></option>
<!--/ko-->
</select>

You could also bind the options in the select tag.

var ViewModel = function(){
  var self = this;
  self.currencyarr = ko.observableArray();
  self.currencyarr(data.curarr);  
}
var data = {
"name" : "shuvagho",
"curarr" : [
            {"id": "inr", "label": "INR"},
            {"id": "usd", "label": "USD"},
            {"id": "aud", "label": "AUD"},
            {"id": "sgd", "label": "SGD"}
]};

var viewModel = new ViewModel();

        ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<select data-bind="options:$root.currencyarr, optionsText: 'label',optionsValue:'id'"></select>