使用angularjs将默认值分配给multiselect下拉列表

时间:2016-01-13 23:37:03

标签: javascript jquery angularjs multi-select

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

如果您查看此页面中的演示部分,请使用'智能按钮文字'演示,因为我正在使用它。

在此演示中,如果您选择任何用户,这些名称将显示在栏中。

现在,我想给它一个默认值。因此,只要页面加载,此多选下拉列表中就会出现一个默认值。

在正常情况下,我可以使用ng-init。在这种情况下我该怎么办?

有人可以在这里说明一点......

4 个答案:

答案 0 :(得分:4)

这是一个小提琴,能够实现您想要实现的目标: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!

回答你的问题 -

  

wat我是否需要使用从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.

答案 1 :(得分:1)

我使用相同的库。 以下是我的工作:

<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。

答案 2 :(得分:0)

您是否尝试使用控制器中的默认值初始化模型?像这样:

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

答案 3 :(得分:0)

我看文件。

我想,

 $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))