简体   繁体   中英

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

This is with reference to fiddle link -->> https://jsfiddle.net/etfLssg4/

As you can see in the fiddle, user can select multiple dropdown items. The dropdown values have been selected during initialization. Lisa and Danny are the default items selected. it gets displayed at the dropdown bar as shown in fiddle.

The default values is set by this line of code.

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

Now the scenario is as follows. The backend data is passed to front end via string. it is as follows

David,Danny

It means David and Danny should be displayed at dropdown. Currently it is "Lisa,Danny"

Heres the explaination of how this should happen. Once we get David,Danny from server side, it will compare with the list of items. From that list, it will come to know that David is number 0 and Danny is 4th of the list.

The list is as follows. (as shown in fiddle)

var items = [{
    id: 1,
    label: "David"
}, {
    id: 2,
    label: "Jhon"
}, {
    id: 3,
    label: "Lisa"
}, {
    id: 4,
    label: "Nicole"
}, {
    id: 5,
    label: "Danny"
}];

Once it knows the number, the code will then display the list of items selected by this line of code.

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

Can someone let me know how to achieve this dynamically. for eg. if string from backend contains only 'lisa', it should display Lisa at the dropdown.

If there are 3 names passed as string from backend, it should be able to show those 3 names at dropdown.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM