【问题标题】:Select option data-bind value with knockout选择带有敲除的选项数据绑定值
【发布时间】:2015-11-28 00:29:33
【问题描述】:
您好,我有一个从 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"}
]
【问题讨论】:
标签:
javascript
jquery
json
knockout.js
【解决方案1】:
使用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>
摆弄示例https://jsfiddle.net/vnoqrgxj/
【解决方案2】:
如果你有:
<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值。
阅读this 了解有关选项绑定的更多信息。