ui-select2 icon indicating copy to clipboard operation
ui-select2 copied to clipboard

One controller for multiple select2s

Open ingog opened this issue 9 years ago • 0 comments

I have multiple select2s on one page. All do the same ajax call, but with one different parameter. So, it would be nice, to have only one controller for all select2s.

In this example I have two select2s. The first makes an ajax call to URL?search=XYZ&attribute=city. The second makes an ajax call to URL?search=XYZ&attribute=street.

<div ng-controller="select2Controller">
  <div aa-select2="select2Config" data-attribute="city" data-ng-model="selection"></div>
  <div aa-select2="select2Config" data-attribute="street" data-ng-model="selection"></div>
</div>

The solution is simple. You could change the code

//AJAX MODE
//run a query to get options (search)
if (inAjaxMode) {
  derivedOpts.query = function (query) {
    settings.options(query.term)

to

//AJAX MODE
//run a query to get options (search)
if (inAjaxMode) {
  derivedOpts.query = function (query) {
    settings.options(query.term, query.element)

Than you can access the select2-element attributes in options-function:

$scope.select2Config = {
  ...
  options: (searchText, element) => {
    var attribute = element.attr("data-attribute");
    return resource.searchValues(attribute, searchText);
  },
};

Thank you.

ingog avatar Sep 03 '14 20:09 ingog