0

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

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

I did all the above coding but still I couldn't able to. It is happening only for observablearray() alone. If I use observable() to display the text it is displaying perfectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.