簡體   English   中英

使用angularjs將默認值分配給multiselect下拉列表

[英]Assign default value to multiselect dropdown using angularjs

我正在使用這個插件http://dotansimha.github.io/angularjs-dropdown-multiselect/#/

如果您在此頁面中查看演示部分,請使用“智能按鈕文本”演示,因為我正在使用它。

在此演示中,如果您選擇任何用戶,這些名稱將顯示在欄中。

現在,我想給它默認值。 因此,只要頁面加載,此多選下拉列表中就會出現一個默認值。

在正常情況下,我可以使用ng-init。 在這種情況下我該怎么辦?

請有人在這里說清楚......

這是一個小提琴,可以實現您想要實現的目標: https//jsfiddle.net/etfLssg4/

這個小提琴的長篇摘要如下:

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

    $scope.example13data = items;

    // here we set the default selections as 'Lisa' and 'Danny'.
    // The point you had missed is that both selection array and options array
    // should have elements with matching references.
    $scope.example13model = [items[2], items[4]];

    $scope.example13settings = {
        smartButtonMaxItems: 3,
        smartButtonTextConverter: function(itemText, originalItem) {
            if (itemText === 'Jhon') {
                return 'Jhonny!';
            }

            return itemText;
        }
    };

如果要以下列方式設置默認選擇(如您所做的那樣):

$scope.example13model = [{
    id: 3,
    label: "Lisa"
}, {
    id: 5,
    label: "Danny"
}];

它不起作用,因為,例如,以下比較評估為false:

items[2] === { id: 3, label: "Lisa" }; // false!

在回答你的問題時 -

如果我需要使用從ajax調用獲得的值更新下拉列表。 例如,在ajax調用之后,我得到一個對象的響應,表明要選擇id 3。 如何將響應綁定到下拉列表,讓用戶看到更新的值

有關問題的解決方案可以解決如下:

var items = [/* as before, this is the list of base options */];
...
...
var dataFromAjax = [/* data here */];
var selection = items.filter(function(item){
    // check if the item matches any one in the ajax data
    return dataFromAjax.some(function(dataItem){
        // assuming the `id` property is unique
        return item.id === dataItem.id;
    });
});
// at this point `selection` is an array with elements that are references to selected option items.

我使用相同的庫。 以下為我工作:

<div ng-dropdown-multiselect options="data.options" selected-model="data.preselected"></div>

$scope.data = {
  options: [
    {id: 1, label: 'one'},
    {id: 2, label: 'two'},
    {id: 3, label: 'three'},
    {id: 4, label: 'four'}
  ],
  preselected: [
    {id: 2, label: 'two'},
    {id: 3, label: 'three'}
  ]
};

編輯

這是工作Plunker我很確定你沒有lodash.js可用。 只需將<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.0.0/lodash.js"></script>到您的html中。

您是否嘗試使用控制器中的默認值初始化模型? 像這樣的東西:

$scope.example13model = [{"id": 1}]

我看文件。

我認為 ,

 $scope.example1data = new Array({id: 1, label: "David"}, {id: 2, label: "Jhon"}, {id: 3, label: "Danny"});



$scope.example1model = new Array();
 //elements that we want to checked
 $scope.example1model.push( $scope.example1data[0])
 $scope.example1model.push( $scope.example1data[1))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM