如何传递后端数据以显示为多选下拉项(附Jsfiddle)

How to pass backend data to display as multiselect dropdown items (Jsfiddle attached)

这是参考fiddle link -->> https://jsfiddle.net/etfLssg4/

如您在 fiddle 中所见,用户可以 select 多个下拉项。下拉值已在初始化期间 selected。 Lisa 和 Danny 是 selected 的默认项目。它显示在下拉栏中,如 fiddle 所示。

默认值由这行代码设置。

$scope.example13model = [items[2], items[4]];

现在的场景是这样的。 后端数据通过字符串传递给前端。如下

David,Danny

这意味着 David 和 Danny 应该显示在下拉列表中。目前是"Lisa,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"
}];

一旦它知道了数字,代码就会显示由这行代码 select编辑的项目列表。

$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;
    });
});