淘汰赛js observableArray不起作用

时间:2016-04-27 09:21:58

标签: javascript arrays json knockout.js

您好我试图使用observableArray做一个foreach而我没有得到任何结果。

在调试数据时javascript文件中的数据正在加载数组。 html代码如下:

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

JSON文件内容如下:

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

使用knockout js的javascript代码如下:

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

1 个答案:

答案 0 :(得分:2)

您忘记在foreach中使用$ data。

  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>

您还可以绑定选择标记中的选项。

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>