Select2允许将“text”键的名称更改为其他名称吗?

17

我有以下的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数组包含具有两个属性命名为idtext的对象,而服务器需要iddescription

请参见我的json代码片段:

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

select2是否允许将文本(text)更改为其他名称?

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


6

以下是使用自定义 id 和文本属性在 ui-select2 上进行配置所必需的最少配置:

$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; }
}

2
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;
});

文档


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接