angular-ui / ui-select2

AngularJS wrapper for select2 (deprecated, use angular-ui/ui-select)
https://github.com/angular-ui/ui-select
MIT License
596 stars 443 forks source link

One controller for multiple select2s #267

Open ingog opened 10 years ago

ingog commented 10 years ago

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.