【问题标题】:How to set default id as 0 for new tags如何将新标签的默认 ID 设置为 0
【发布时间】:2014-08-19 10:27:04
【问题描述】:

如何为不在列表中的标签设置默认id为0?

[DEMO LINK][1]

LINK

在上面的例子中,如果我们从现有的中选择,那么它带有 id(1 或 2 或 3),但如果添加新标签并按 enter 则 id 变为文本,我希望 id 设置为 o 表示新标记或不在列表中。

怎么做?

【问题讨论】:

  • 你的 plunker 似乎坏了
  • 拒绝执行来自 'raw.githubusercontent.com/angular-ui/ui-select2/master/src/…' 的脚本,因为它的 MIME 类型 ('text/plain') 不可执行,并且启用了严格的 MIME 类型检查。跨度>
  • @Malkus 更新了我的 plunkr,请查看
  • @Jai 更新了我的 plunkr,请查看

标签: angularjs jquery-select2 ui-select2 angularjs-select2


【解决方案1】:

CreateSearchChoice 应该是您要查找的内容

这是我不久前问过的一个类似的 SO select2 createSearchChoice id from post

createSearchChoice: function (term, data) {
    if ($(data).filter(function () {
            return this.text.localeCompare(term) === 0;
        }).length === 0) {
            // if not found in current list
            // return {id:term, text:term}

            return {
            id: term,
            text: $.trim(term) + ' (new tag)'
            };

},

请注意,我将 id 设置为新的文本术语,您可以将其设置为像 -1/term 这样的连接值,然后稍后将其解析出来,但术语必须包含在此解决方案的 ID 中

然后在更改事件中,我确定 id 是否为数字(已经存在)。如果它不是数字(在 createsearchchoice 中添加),我将完成发布到标签数据库的过程

.on("change", function(e) {
    if (e.added) { //is it added from select2
    if (isNumeric(e.added.id)){ //did it already exist or createsearchchoice
        add(e.added.id); //it already existed, just add it to the tag list
        } else { //id was created on the fly, post to the database and return a tag id
            $.post('handlers/tags.ashx', { 
               operation:"select2createtag", 
               //because its not numeric, we know id = new tag text
               text: $.trim(e.added.id)} ,   
               function(data){
               //set the added id to the id you just returned from sql
                e.added.id = data.id;
                //...do something else, like then add the new tag to the item

                });
              };
            };

如果您不想发布到 ajax,请让您的服务器端评估您的输入项,以及任何 id 的非数字标签,请遵循上述相同的想法

I updated your Plunker here

【讨论】:

  • Thx ,我已经尝试了您的代码并扩展了它的工作。我的意思是我的 ID 为 0,但它只允许我输入一个新标签,之后它不会添加新标签。我已经更新了我的 plunkr,请 chk
  • 它不允许将 id 设置为 0,这就是为什么我在 plunkr 中保留 '00'。
  • 我更新了答案和 Plunker...请注意,如果您希望它是动态的,您可能需要更改标签的静态分配
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多