解决方案:
我自己想通了:申请this fix后整个问题就不再是问题了并进行 ui-select 的自定义构建。我希望这很快就会进入官方主分支!
问题
如何初始化具有多个值的选择?我正在尝试此操作,但它没有显示选择中的选定项目。
首先,我认为这与我通过 HTTP get 异步获取的数据有关,但即使是我为展示问题而制作的“静态”plunker 示例也不适合我。
我认为我的问题是数据来自两个不同的源,因此两个数组之间的索引和引用不匹配。类别列表是通过服务获取的,所选类别来自另一个服务,该服务与附加到它们的数据集一起返回。在另一个选择中,加载所有 45,000 个用户只是为了从这个巨大的列表中选择选定的用户是非常不切实际的。
那么我怎样才能让现有的选择数据出现在 ui-select 中呢?
HTML
<body ng-controller="MainCtrl">
<label>Assigned Categories</label>
<ui-select
multiple
ng-model="categories.selected"
on-select="selectCategory($item, $model)"
on-remove="deselectCategory($item, $model)">
<ui-select-match placeholder="Select Category...">{{$item.name}}</ui-select-match>
<ui-select-choices
repeat="category in categories.categories track by category.id">
{{category.name}}
</ui-select-choices>
</ui-select>
<pre>{{categories | json}}</pre>
</body>
JS
var app = angular.module('plunker', [
'ui.select'
]);
app.controller('MainCtrl', function($scope) {
$scope.categories = {
selected: [
{
"id": "1",
"name": "Foo"
}
],
categories: [
{
"id": "1",
"name": "Foo 1"
},
{
"id": "2",
"name": "Bar 2"
},
{
"id": "3",
"name": "FooBar 3"
}
]
};
});
最佳答案
“初始化”select
或 ui-select
或任何其他 ng-model
类型输入的方法是通过设置进入 ng-model 的 ViewModel 变量可以是您想要的任何选定值或对象(如本例所示)。
您尝试在示例中执行此操作,但由于您正在选择一个对象,因此您的虚拟机应该引用同一对象(通过引用)。您的错误是您创建了具有相同内容的不同对象。
因此,$scope.categores.selected
应该是实际对象的数组(因为它是多个
):
$scope.categories = {
categories: [
{
"id": "1",
"name": "Foo 1"
},
{
"id": "2",
"name": "Bar 2"
},
{
"id": "3",
"name": "FooBar 3"
}
]
};
$scope.categories.selected = [$scope.categories.categories[0]];
关于javascript - AngularJS ui-select,如何初始化多选值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28068795/