这是一个你想要实现的小提琴:https://jsfiddle.net/etfLssg4/
该小提琴的详细摘要如下:
var items = [{
id: 1,
label: "David"
}, {
id: 2,
label: "Jhon"
}, {
id: 3,
label: "Lisa"
}, {
id: 4,
label: "Nicole"
}, {
id: 5,
label: "Danny"
}];
$scope.example13data = items;
// here we set the default selections as 'Lisa' and 'Danny'.
// The point you had missed is that both selection array and options array
// should have elements with matching references.
$scope.example13model = [items[2], items[4]];
$scope.example13settings = {
smartButtonMaxItems: 3,
smartButtonTextConverter: function(itemText, originalItem) {
if (itemText === 'Jhon') {
return 'Jhonny!';
}
return itemText;
}
};
如果要按以下方式设置默认选择(您可能已经这样做了):
$scope.example13model = [{
id: 3,
label: "Lisa"
}, {
id: 5,
label: "Danny"
}];
这是行不通的,因为例如,下面的比较结果为假:
items[2] === { id: 3, label: "Lisa" }; // false!
回答你的问题 -
如果我需要使用从 ajax 获得的值更新下拉列表
称呼。例如在ajax调用之后,我在一个对象中得到一个响应
id 3 将被选中。我如何将响应绑定到下拉列表和
让用户看到更新后的值
?
该问题的解决方法如下:
var items = [/* as before, this is the list of base options */];
...
...
var dataFromAjax = [/* data here */];
var selection = items.filter(function(item){
// check if the item matches any one in the ajax data
return dataFromAjax.some(function(dataItem){
// assuming the `id` property is unique
return item.id === dataItem.id;
});
});
// at this point `selection` is an array with elements that are references to selected option items.