2016-01-15 13 views
0

這是參照小提琴鏈接 - >>https://jsfiddle.net/etfLssg4/如何通過後端數據顯示爲多選下拉項(附的jsfiddle)

正如你可以在小提琴看到,用戶可以選擇多個下拉項目。初始化期間已選擇下拉值。 Lisa和Danny是所選的默認項目。它將顯示在下拉條中,如小提琴中所示。

默認值由該行代碼設置。

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

現在情況如下。 後端數據通過字符串傳遞給前端。它如下

David,Danny 

這意味着大衛和丹尼應該在下拉菜單中顯示。目前它是「麗莎,丹尼」

繼承人解釋如何發生這種情況。一旦我們從服務器端得到大衛,丹尼,它將與項目列表進行比較。從列表中,它會知道大衛是0號,丹尼是名單中的第4名。

清單如下。 (如小提琴所示)

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個名稱。

回答

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

試過這個,但它給出了未定義的結果在下拉欄中。 – Ayesha

+0

$ scope.example13model = res應該類似於這種形式。 $ scope.example13model = [items [0],items [4]]; – Ayesha

+1

你可以嘗試使用過濾器 'var str =「David,Lisa」; var splt = str.split(「,」); VAR項= [{ ID:1, 標籤: 「大衛」 },{ ID:2, 標籤: 「JHON」 },{ ID:3, 標籤: 「LISA」 } { id:4, label:「Nicole」 },{ id:5, label:「Danny」 }]; VAR REZ = items.filter(函數(名稱){ 回報(splt.indexOf(name.label)> -1); }) $ scope.example13model =蘇亞雷斯;' 我會更新的答案: D –

相關問題