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

坚强是说给别人听的谎言 提交于 2020-01-07 05:24:10

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/34802084/how-to-pass-backend-data-to-display-as-multiselect-dropdown-items-jsfiddle-atta

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!