首页 > 解决方案 > select2 4.0.8,templateSelection 选项不起作用

问题描述

我正在使用带有 ajax 搜索的select2版本。4.0.8在我的带有 ajax 调用的 Angular 4 应用程序中。直到搜索和填充结果它工作正常。但在那之后,当我点击任何选项时,它不会调用templateSelection选项中指定的方法。

下面是我正在使用的代码:

jQuery(".suggestion"+i).select2({
  placeholder: 'Select Countries',
  ajax: {
    url: AppConstants.facebookBaseUrl + "/search",
    dataType: 'json',
    delay: 250,
    type: "GET",
    beforeSend: (request)=> {
      request.setRequestHeader("Authorization", "Bearer "+this.user.facebookPage_Token);
    },
    data: (params)=> {
      return {
        q: params.term, // search term
        location_types: this.facebookFilters[i].filter,
        type: "adgeolocation",
        page: params.page
      };
    },
    processResults: function (data, params) {

      // parse the results into the format expected by Select2
      // since we are using custom formatting functions we do not need to
      // alter the remote JSON data, except to indicate that infinite
      // scrolling can be used
      params.page = params.page || 1;

      return {
        results: data.data,
        pagination: {
          more: (params.page * 30) < data.total_count
        }
      };
    },
    cache: true
  },
  multiple:true,
  minimumInputLength: 2,
  templateResult: formatRepo,
  templateSelection: formatRepoSelection
});

function formatRepo (repo) {
  if (repo.loading) {
    return repo.text;
  }      
  var $container = jQuery("<option (click)='selectCountry($event)' class='country_name' value='"+repo.key+"'>"+repo.name+"</option>");
  return $container;
}

function formatRepoSelection (repo) {
  var $container = jQuery("<option class='selectedCountry' value='"+repo.key+"'>"+repo.name+"</option>");
  return $container;
  // return repo.key || repo.text;
}

和 HTML:

<select class="form-control" name="selected[]" [ngClass]="'suggestion'+i"></select>

我在这里做错了什么?提前致谢!

标签: ajaxangularjquery-select2

解决方案


尝试更改optionspan

function formatRepoSelection (repo) {
  var $container = jQuery("<span class='selectedCountry'>"+repo.name+"</span>");
  return $container;
  // return repo.key || repo.text;
}

推荐阅读