更新时间:2023-02-11 19:55:31
这是一个小提琴,可以实现您想要实现的目标: https://jsfiddle.net/etfLssg4/
Here's a fiddle that does what you want to achieve: https://jsfiddle.net/etfLssg4/
该小提琴的长摘要如下:
A long summary of that fiddle is as follows:
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;
}
};
如果要以下列方式设置默认选择(如您所做的那样):
If the default selection were to be set in the following manner (as you probably did):
$scope.example13model = [{
id: 3,
label: "Lisa"
}, {
id: 5,
label: "Danny"
}];
它不起作用,因为,例如,以下比较评估为false:
It wouldn't work because, for instance, the following comparison evaluates to false:
items[2] === { id: 3, label: "Lisa" }; // false!
回答你的问题 -
In answer to your question -
wat如果我需要使用从ajax
调用获得的值更新下拉列表。例如在ajax调用之后,我在一个对象中得到一个响应,表明要选择
id 3。如何将响应绑定到下拉列表,
让用户看到更新后的值
wat if i need to update the dropdown with values i get from a ajax call. for e.g. after ajax call, i get a response in an object stating id 3 is to be selected. how do i bind the response to the dropdown and let the user see the updated value
?
有问题的解决方案可以解决如下:
The solution to the issue in question can be resolved as follows:
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.