使用angularjs将默认值分配给multiselect下拉列表 [英] Assign default value to multiselect dropdown using angularjs
问题描述
我正在使用此插件 http://dotansimha.github.io/angularjs- dropdown-multiselect /#/
如果您在此页面中查看演示部分,请使用智能按钮文本演示,因为我正在使用它。
If you check the demo part in this page, please use the ' Smart Button Text ' Demo as i am using that.
在此演示中,如果您选择任何用户,这些名称将显示在栏中。
In this demo, if you select any users, those names will be displayed in the bar.
现在,我想给它提供默认值。因此,只要页面加载,此多选下拉列表中就会出现一个默认值。
Now, i want to give default value to it. So as soon as the page loads, there will be a default value present in this multiselect dropdown.
在正常情况下,我可以使用ng-init。在这种情况下我该怎么办?
In normal case, i can use ng-init. What should i do in this case ?
请有人在这里说清楚......
Can someone shed some light here please.....
推荐答案
这是一个小提琴,可以实现您想要实现的目标: 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.
这篇关于使用angularjs将默认值分配给multiselect下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!