简体   繁体   中英

knockout js observableArray is not working

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

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> 

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