Ad

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.

Ad

Answer

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;
    });
});
Ad
source: stackoverflow.com
Ad