【问题标题】:select2 4.0.8, templateSelection option not workingselect2 4.0.8,templateSelection 选项不起作用
【发布时间】:2019-08-13 06:59:33
【问题描述】:

我正在使用带有 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>

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

【问题讨论】:

  • 供将来参考:您可能在 ajax 响应中缺少参数 id。响应应包含唯一变量id

标签: ajax angular jquery-select2


【解决方案1】:

尝试将option 更改为span

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

【讨论】:

  • 完全没有变化。结果被正确填充,但之后它就不起作用了。我的意思是当我单击以li 形式存在的选项时不起作用。
  • @JayeshChoudhary 你能用你的代码创建 stackblitz 吗?
  • 嗨,请在这里找到详细信息:stackblitz.com/edit/angular-kggcsp 我还需要多选。
猜你喜欢
  • 2015-05-22
  • 1970-01-01
  • 2013-07-12
  • 1970-01-01
  • 2019-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-25
相关资源
最近更新 更多