使用对象数组中的 ID 设置 ui-select 值

Set ui-select value using ID from an array of objects

嗯,我有这种格式的对象数组

$scope.itemArray = [
        {id: 1, name: 'first'},
        {id: 2, name: 'second'},
        {id: 3, name: 'third'},
        {id: 4, name: 'fourth'},
        {id: 5, name: 'fifth'},
    ];

$scope.selectedItem = $scope.itemArray[0];//this works fine
$scope.selectedItem = $scope.itemArray[0].id;//this doesn't works


这是 html 部分:

<ui-select ng-model="selectedItem">
    <ui-select-match>
        <span ng-bind="$select.selected.name"></span>
    </ui-select-match>
    <ui-select-choices repeat="item in itemArray | filter: $select.search">
        <span ng-bind="item.name"></span>
    </ui-select-choices>
  </ui-select>

我想做的是使用 id 列设置 ui-select 值,但我无法这样做。我确信我在某个地方错了,而且这个插件也很新。请帮助我。

使用以下内容更改您的 ng-repeat:

<ui-select ng-model="selectedItem">
    <ui-select-match>
        <span ng-bind="$select.selected.name"></span>
    </ui-select-match>
    <ui-select-choices repeat="item.id as item in itemArray | filter: $select.search">
        <span ng-bind="item.name"></span>
    </ui-select-choices>
</ui-select>

Demo

您可以在此 git 页面中找到有关此插件的更多信息。 https://github.com/angular-ui/ui-select/wiki/ui-select-choices