使用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.
我使用相同的库。 以下为我工作:
$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
可用。 只需将到您的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))