0

I created a select2 element with CiviCRM's crmUiSelect AngularJS directive by using the following code in my controller:

$scope.options = [
  {"value": "foo", "label": "Foo"},
  {"value": "bar", "label": "Bar"},
  {"value": "baz", "label": "Baz"},
  {"value": "bat", "label": "Bat"}
];

and the following code in my template:

<select
  crm-ui-select="{allowClear: true}"
  ng-model="myVar"
  ng-options="option as option.label for option in options track by option.value"
  multiple="multiple"
  class="big"
>
</select>

{{myVar}}

It sort of worked, but here's what I ended up with:

screenshot

As you can see in the above screenshot, this element has the following problems:

  • myVar is an array with only one element, even when multiple options are selected.
  • The list of options contains options which have already been selected (and the element actually allows these options to be selected more than once).

How can I fix this element so that it works as expected? I want myVar to become ["foo", "bar"] in the screenshot above, and I want the user to only see options which have not already been selected.

1

For some reason, you can't use the ngOptions directive with select2 multi-select elements. You need to manually specify the <option> elements with ngRepeat like this instead:

<select
  crm-ui-select="{allowClear: true}"
  ng-model="myVar"
  multiple="multiple"
  class="big"
>
  <option ng-repeat="option in options" value="{{option.value}}">
    {{option.label}}
  </option>
</select>

{{myVar}}

That produces the desired behavior:

screenshot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.