[英]Select option data-bind value with knockout
嗨,我有一個從Web API返回的可觀察數組。
1)如何將返回的jSon如下綁定到視圖模型,以及如何在視圖中訪問它?
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"} ]
使用observableArrays
。 像這樣:
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();
}
您認為:
<div data-bind="foreach: animals">
<label data-bind="text:animalname"></label>
</div>
如果你有:
<select data-bind="options: animalOptions,
optionsText: 'animalname',
optionsValue: 'animalid',
value: selectedAnimal,
optionsCaption: 'Select animal'">
</select>
作為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());
對於最初選擇的選項,設置self.selectedAnimal = "two"
即所需選擇的animalid
值。
閱讀此內容以獲得有關選項綁定的更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.