javascript - AngularJS ui-select,如何初始化多选值?

标签 javascript angularjs select angular-ui

解决方案:

我自己想通了:申请this fix后整个问题就不再是问题了并进行 ui-select 的自定义构建。我希望这很快就会进入官方主分支!

问题

如何初始化具有多个值的选择?我正在尝试此操作,但它没有显示选择中的选定项目。

首先,我认为这与我通过 HTTP get 异步获取的数据有关,但即使是我为展示问题而制作的“静态”plunker 示例也不适合我。

我认为我的问题是数据来自两个不同的源,因此两个数组之间的索引和引用不匹配。类别列表是通过服务获取的,所选类别来自另一个服务,该服务与附加到它们的数据集一起返回。在另一个选择中,加载所有 45,000 个用户只是为了从这个巨大的列表中选择选定的用户是非常不切实际的。

那么我怎样才能让现有的选择数据出现在 ui-select 中呢?

Plunker link.

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"
        }
            ]
        };
});

最佳答案

“初始化”selectui-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/

相关文章:

android - sqlite android select col(x) where (col1 like '%key%' ) or (col2 like '%key%' ) - x 是包含键的列

javascript - 具有有限高度和宽度的 D3 SVG

javascript - async/await 函数不等待 setTimeout 完成

angularjs - Protractor 找不到之前已找到 2 个测试的元素

c# - Angular JS - UI 测试 Angular js 项目的最佳方式

mysql - 从 mysql 表中选择每隔一行作为男性/女性

SQL SELECT 当子表包含零行时

javascript - jQuery 验证 - 同一类的 NotEqual 验证

javascript - 将 Firebase 实时数据库与 Google 应用引擎 Web 应用集成(Python API)

javascript - AngularJS 路由和 jQuery 冲突