[英]Binding ko.observableArray<string>([]) to <select>
I am trying to bind a string array to a <select>
. 我正在尝试将字符串数组绑定到<select>
。 I try to bind it initially but keep getting a message that someOptions
is undefined. 我最初尝试绑定它,但不断收到一条消息,指出someOptions
未定义。 I have try to move it in "Load Button" click event but it didn't seem to work either. 我尝试在“加载按钮”单击事件中将其移动,但它似乎也不起作用。 Anyone has any idea where went wrong? 有人知道哪里出了问题吗?
My Code: 我的代码:
function CarsViewModel() {
var self = this;
//Data
self.someOptions = ko.observableArray<string>([]);
self.myOption = ko.observable<string>("Toyota");
//Operations
self.initData = function () {
//$.get('/Home/GetCars', function (data) {
var data = [
"Mercedes-Benz",
"Toyota",
"Huyndai" ];
self.someOptions(data);
//});
}
//self.initData()
}
ko.applyBindings(new CarsViewModel());
<div>
<button data-bind="click: initData">Load data</button>
<h4>Preview</h4>
<p>
<select data-bind="options: someOptions, value: myOption"></select><br />
<!-- ko with: myOption -->
A <span data-bind="text: myOption"></span>.
<!-- /ko -->
</p>
</div>
You have multiple problems in your code: 您的代码中有多个问题:
observable<string>
or generics in javascript proper, you should get rid of it; javascript中没有observable<string>
或泛型这样的东西,您应该摆脱它; with: myOption
but inside it you refer to myOption
again . 您可以with: myOption
但在其中可以再次引用myOption
。 Use either $data
or get rid of the with
, or use if
if you want to show/hide the entire thing optionally; 请使用$data
或摆脱with
,或使用if
你想显示/隐藏可选整个事情; myOption
but that's confusing / useless, as the rendering of the select
will overwrite it to empty string on load; 您设置了myOption
的初始值,但这很令人困惑/无用,因为select
的呈现将在加载时将其覆盖为空字符串; With those things fixed everything works: 修复了这些问题后,一切正常:
function CarsViewModel() { var self = this; self.someOptions = ko.observableArray([]); self.myOption = ko.observable(""); self.initData = function () { var data = ["Mercedes-Benz", "Toyota", "Huyndai" ]; self.someOptions(data); } } ko.applyBindings(new CarsViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> <div> <button data-bind="click: initData">Load data</button> <h4>Preview</h4> <p> <select data-bind="options: someOptions, value: myOption"></select> <br /> <!-- ko if: !!myOption() --> A <span data-bind="text: myOption"></span>. <!-- /ko --> </p> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.