首页 > 解决方案 > 使用闪亮的选择,避免对搜索结果进行排序

问题描述

在下面的可重现闪亮应用程序中,可搜索的选择字段按字符串的长度重新排序值。

在此处输入图像描述

如果我1在搜索字段中键入,则 'Gears' 会出现在 'Cylinders' 上方,因为字符串更短。但是,我希望它们按原始顺序,即 11 高于 12 高于 13。

selectize repo中的一个线程建议添加类似的东西sortField: [{field: 'name', direction: 'asc'}],但我没有设法在闪亮的上下文中添加它。所以添加options = list(sortField = list(field = 'name', direction = 'asc'))selectizeInput()没有效果。

library(shiny)
choices <- c(
  "11 Cylinders" = "cyl",
  "12 Transmission" = "am",
  "13 Gears" = "gear"
)

shinyApp(
  ui = fluidPage(
    selectizeInput(
      "variable", 
      "Variable:", 
      choices
    )
  ),
  server = function(input, output) {
  }
)

标签: rshiny

解决方案


library(shiny)

# must have named vector for selectize.js to pick up on the injection
choices <- c(
  "11 Cylinders" = "cyl",
  "12 Transmission" = "am",
  "13 Gears" = "gear"
)

# define JS to inject for options
##asceding order
sort_asc <- I("[{field: 'name', direction: 'asc'},{field: '$score'}]")

##decending order
sort_desc <- I("[{field: 'name', direction: 'desc'},{field: '$score'}]")

JS_opts <- list(create=TRUE,
                labelField =  'name',
                searchField = 'name',
                sortField = sort_asc
                )

shinyApp(
  ui = fluidPage(
    selectizeInput(
      inputId = "variable", 
      label = "Variable:", 
      choices = choices,
      options = JS_opts
    )
  ),
  server = function(input, output) {
  }
)


推荐阅读