2015-09-27 20 views
0

我正在嘗試使用Select2.js版本4.0創建標記選擇。我想要創建一個新的標籤,如果它沒有退出,並且我希望使用'data-html'標籤格式化結果。Select2模板在標記時不會自動完成

問題是兩個元素(createTagtemplateResult)獨立工作,但是當我將它們一起使用時,當用戶在搜索框中鍵入內容時,不再顯示自動填充選項。

我做錯了什麼,或者這是一個限制的Select2?

的application.js

$("#taglist").select2({ 
    tokenSeparators: [',', ' '], 
    tags: true, 
    createTag: function (tag) { 
     // Case insensitive search for tag 
     tagExists = false; 
     $("#taglist option").each(function() { 
      if ($.trim(tag.term).toUpperCase() == $.trim($(this).text()).toUpperCase()) { 
       tagExists = true; 
      } 
     }); 

     // If the tag does not exist create it 
     if (!tagExists) { 
      return { 
       id: tag.term, 
       text: tag.term + " (create)", 
       isNew: true 
      }; 
     } 
    }, 
    templateResult: function (choice) { 
     if (!choice.id) { return choice.text; } 
     var $choice = $(
     '<span><a>' + data.element.getAttribute('data-html') + '</a></span>' 
    ); 
     return $choice; 
    } 
    }); 

回答

0

標記時,讓你的模板方法必須能夠處理沒有data.element。理想情況下,你的方法應該能夠與data.text一起工作,其他任何東西都是可選的。

因此,如果元素上的data-html屬性中沒有任何內容,那麼您應該回退到data.text