16

我有以下 Select2 配置。

$scope.select2Options = {
    simple_tags: false,
    placeholder : "Search for a language",
    multiple : true,
    contentType: "application/json; charset=utf-8",
    minimumInputLength : 3,
    ajax : {
        url : "/bignibou/utils/findLanguagesByLanguageStartingWith.json",
        dataType : 'json',
        data : function(term) {
            return  {
                language : term
            };
        },
        results : function(data, page) {
            return {
                results :
                    data.map(function(item) {
                        return {
                            id : item.id,
                            text : item.description
                        };
                    }
            )};
        }
    }
};

这使我可以正确填充 select2 控件。

但是,当我使用 Ajax 发布包含标签(以及其他)的整个表单时会出现一个问题:发送到服务器的 json 数组包含具有两个名为idand的属性的对象,text而服务器需要idand description

从我的 json 中查看片段:

"languages":[{"id":46,"text":"Français"},{"id":1,"text":"Anglais"}]

select2 是否允许将名称更改为text其他名称?

4

3 回答 3

16

将我的 js 更改为以下对问题进行了排序:

function format(item) { return item.description; };

$scope.select2Options = {   
    simple_tags: false,
    placeholder : "Search for a language",
    multiple : true,
    contentType: "application/json; charset=utf-8",
    minimumInputLength : 3,
    data:{ text: "description" },
    formatSelection: format,
    formatResult: format,
    ajax : {
        url : "/bignibou/utils/findLanguagesByLanguageStartingWith.json",
        dataType : 'json',
        data : function(term) {
            return  {
                language : term
            };
        },
        results : function(data, page) {
            return {
                results :
                    data.map(function(item) {
                        return {
                            id : item.id,
                            description : item.description
                        };
                    }
            )};
        }
    }
};

注意:必须使用 Select2 顶级属性data

于 2013-10-14T11:19:15.617 回答
6

这是在 ui-select2 上使用自定义 id 和 text 属性所必需的最低配置

$scope.clients: {
  data: [{ ClientId: 1, ClientName: "ClientA" }, { ClientId: 2, ClientName: "ClientB" }],
  id: 'ClientId',
  formatSelection: function (item) { return item.ClientName; },
  formatResult: function (item) { return item.ClientName; }
}
于 2014-01-16T22:16:32.277 回答
1

Select2 要求应为选项显示的文本存储在 text 属性中。您可以使用以下 JavaScript 从任何现有属性映射此属性:

var data = $.map(yourArrayData, function (obj) {
  obj.text = obj.text || obj.name; // replace name with the property used for the text
  obj.id = obj.id || obj.pk; // replace pk with your identifier
  return obj;
});

文档

于 2019-04-30T08:45:24.487 回答