Search code examples
angularjsui-selectangular-ui-select

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


Well I have the array of objects in this format

$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


and this is the html part:

<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>

What I am trying to do is set the ui-select value using the id column, but I am unable to do so. I am sure that I am wrong somewhere and also very much new to this plugin. Please help me.


Solution

  • Change your ng-repeat with the following:

    <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

    You can find more information about this plugin in this git page. https://github.com/angular-ui/ui-select/wiki/ui-select-choices