[英]Select option data-bind value with knockout
Hi I have a observable array return from a web API. 嗨,我有一个从Web API返回的可观察数组。
1) How to I bind the return jSon as follows to the view model and how do I access it in view? 1)如何将返回的jSon如下绑定到视图模型,以及如何在视图中访问它?
2) Since there is no information about which option is selected from the returned jSon, how do I make the view initially display the selected option based on the self.selectedAnimal
(which is the selected text)? 2)由于没有有关从返回的jSon中选择哪个选项的信息,我如何使视图最初基于
self.selectedAnimal
(即所选文本)显示所选选项?
function NewViewModel() { var self = this; self.selectedAnimal = "Cat"; self.GetAnimal() { $.ajax({ url:"http:/abc.com/api/GetAnimalList", dataType: "json", type: "GET", data: {} success: function() { // What to assign here } }); } } ko.applyBindings(new NewViewModel()); // example of json return "animals": [ { "animalid": "1", "animalname": "cat" }, { "animalid": "two", "animalname": "dog" }, { "animalid": "three", "animalname": "horse"} ]
Use observableArrays
. 使用
observableArrays
。 Like this: 像这样:
function NewViewModel() {
var self = this;
self.selectedAnimal = ko.observable('Cat');
self.animals = ko.observableArray();
self.getAnimals = function() {
$.ajax({
url:"http:/abc.com/api/GetAnimalList",
dataType: "json",
type: "GET",
data: { }
success: function(animals) {
self.animals(animals);
}
});
};
//reload the animals
//load the view
self.getAnimal();
}
In your view: 您认为:
<div data-bind="foreach: animals">
<label data-bind="text:animalname"></label>
</div>
Fiddle with example https://jsfiddle.net/vnoqrgxj/ 摆弄示例https://jsfiddle.net/vnoqrgxj/
If you have: 如果你有:
<select data-bind="options: animalOptions,
optionsText: 'animalname',
optionsValue: 'animalid',
value: selectedAnimal,
optionsCaption: 'Select animal'">
</select>
As select markup in HTML, then in your view model add the animalOptions
array and fill that when the ajax request returns success. 作为HTML中的选择标记,然后在视图模型中添加
animalOptions
数组,并在ajax请求返回成功时进行填充。
function NewViewModel() {
var self = this;
self.selectedAnimal = "two"; // initial selection as 'dog'
self.animalOptions = ko.observableArray([]);
function GetAnimal() {
$.ajax({
url:"http:/abc.com/api/GetAnimalList",
dataType: "json",
type: "GET",
data: {},
success: function(data) {
// What to assign here
$.each(data.animals, function(i,option){
self.animalOptions.push(option);
});
}
});
}
GetAnimal();
}
ko.applyBindings(new NewViewModel());
For the initially selected option, set self.selectedAnimal = "two"
ie the animalid
value of desired selection. 对于最初选择的选项,设置
self.selectedAnimal = "two"
即所需选择的animalid
值。
Read this for more information about options binding. 阅读此内容以获得有关选项绑定的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.