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

Assign default value to multiselect dropdown using angularjs

本文关键字:下拉列表 分配 angularjs 默认值 使用      更新时间:2023-09-26

我正在使用这个插件 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!

回答你的问题——

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.

我使用相同的库。以下对我有用:

<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'}
  ]
};

编辑

这是工作普伦克我很确定你没有可用的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))