lostintranslation
lostintranslation

Reputation: 24583

Is it possible to use single select but get model as an array

I am using angular-ui's select2 component and I would like to have consistent values for my models whether I am using single select or multi select.

Currently if I use single select the model is just set to one value, when using multi select the model is an array of values.

IE single select: (non array model)

<ui-select ng-model="model.value" theme="bootstrap">
  <ui-select-match>{{$select.selected.title}}</ui-select-match>
  <ui-select-choices repeat="choice.title as choice in choices | filter: $select.search">
    <div ng-bind-html="choice.title | highlight: $select.search"></div>
  </ui-select-choices>
</ui-select>

Or multi: (array model)

<ui-select multiple ng-model="model.value" theme="bootstrap">
  <ui-select-match>{{$item.title}}</ui-select-match>
  <ui-select-choices repeat="choice.title as choice in choices">
    <div ng-bind-html="choice.title"></div>
  </ui-select-choices>
</ui-select>

I tried using multiple, and adding length="1" attribute, however that still applies the multiselect styles to the select box.

Would it be possible to get an array model back from select2 even on single select?

Upvotes: 0

Views: 676

Answers (1)

Brian
Brian

Reputation: 5049

How about setting the model to be the first position in an array by changing ng-model="model.value" to ng-model="model.value[0]"? I believe that should work. If not, try initializing the model in the controller first as an empty array. ($scope.model = [];)

<ui-select ng-model="model.value[0]" theme="bootstrap">
  <ui-select-match>{{$select.selected.title}}</ui-select-match>
  <ui-select-choices repeat="choice.title as choice in choices | filter: $select.search">
    <div ng-bind-html="choice.title | highlight: $select.search"></div>
  </ui-select-choices>
</ui-select>

Upvotes: 2

Related Questions