javascriptangularjsangular-uiui-selectangular-ui-select

Angularjs UI multiselect with initial selection


I am using Angularjs UI select. I'm facing a problem.

This is my code:

Javascript:

$scope.user.SelectedCategories
$scope.Categories= [
  { value: 'Reading', name: 'Reading Books',Id : 4 },
  { value: 'Sports', name: 'Physical Activity',Id : 9 },
  { value: 'Movies', name: 'Entertainment',Id : 7 },
  { value: 'Video Games', name: 'Passion',Id : 11 }
];

HTML:

<div class="input-group">
      <ui-select multiple ng-model="user.SelectedCategories" theme="bootstrap" sortable="true" close-on-select="false" style="width: 350px;">
      <ui-select-match placeholder="Select Categories...">{{$item.Value}}</ui-select-match>
      <ui-select-choices repeat="category.Id as category in  Categories">{{category.Value}}
      </ui-select-choices>
</div>

Now how can I display selected categories as selected on page reload.Selected categories will be saved in the database and on page reload they will be available on the client side but how can I show them as selected and they also must not appear in the dropdownlist.

Edit Half of my problem is solved by nicost's suggestion of assigning selected categories fetched from database to $scope.SelectedCategories but the rest of the problem is those categories also appear in the dropdown.

The default behavior of ui multiselect is that if I select one category from the dropdown it is displayed in the textbox above as selected and that category is removed from the dropdown list and when I remove any category from the selected categories that category appears in the dropdownlist.

In my case If I remove selected categories from available Categories' list(I'm doing that on the server side) on page reload then they dont appear in the dropdowm but when I remove any selected category that category does not appear in the dropdownlist.


Solution

  • To prevent showing selected categories in your dropdown, you have to filter the values in there. You can do this with a custom filter:

    <ui-select-choices  repeat="category in categories | filter: $select.search |filter:customFilter track by category.Id">
    

    I created a plunker for you. I hope this helps.