这是引用 fiddle 链接 -->> https://jsfiddle.net/etfLssg4/
正如您在 fiddle 中看到的,用户可以选择多个下拉项。下拉值已在初始化期间选择。 Lisa 和 Danny 是默认选择的项目。它显示在下拉栏中,如 fiddle 所示。
默认值由这行代码设置。
$scope.example13model = [items[2], items[4]];
现在的场景如下。 后端数据通过字符串传递给前端。如下
David,Danny
这意味着 David 和 Danny 应显示在下拉列表中。目前是“丽莎,丹尼”
这是如何发生这种情况的解释。一旦我们从服务器端获取 David、Danny,它将与项目列表进行比较。从该列表中,我们可以知道 David 是第 0 号,Danny 是列表中的第 4 号。
列表如下。 (如 fiddle 所示)
var items = [{
id: 1,
label: "David"
}, {
id: 2,
label: "Jhon"
}, {
id: 3,
label: "Lisa"
}, {
id: 4,
label: "Nicole"
}, {
id: 5,
label: "Danny"
}];
一旦知道该数字,代码就会显示该行代码选择的项目列表。
$scope.example13model = [items[0], items[4]];
有人可以让我知道如何动态实现这一点吗?例如。如果来自后端的字符串仅包含“lisa”,则它应该在下拉列表中显示 Lisa。
如果有 3 个名称作为字符串从后端传递,它应该能够在下拉列表中显示这 3 个名称。
最佳答案
var items = [{
id: 1,
label: "David"
}, {
id: 2,
label: "Jhon"
}, {
id: 3,
label: "Lisa"
}, {
id: 4,
label: "Nicole"
}, {
id: 5,
label: "Danny"
}];
var backendSelection = "David,Lisa";
var selectedLabels = backendSelection.split(",");
$scope.example13model = items.
filter(function(item) {
// if the the label property of the current item
// is found in selectedLabels, return true (i.e. allow the current item
// to pass through the filter) otherwise false.
return selectedLabels.some(function(label) {
// whenever the following expression evaluates to true,
// the current item will be selected.
return label === item.label;
});
});
关于javascript - 如何传递后端数据以显示为多选下拉项(附Jsfiddle),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34802084/