在我的 Shiny 应用程序中,我有一个带有 selectInputs 的 DT 数据表,该数据表会根据用户输入进行更新。我使用 JavaScript 来绑定/取消绑定 selectInputs 并选择它们以实现样式设置和搜索功能。我使用 DT::datatableProxy() 和 DT::replaceData() 来更新数据表中的 selectInputs,而不是闪亮的::updateSelectInput()。这是因为在我的真实应用程序中, selectInputs 可能会从表中删除或添加以响应用户输入。 我有一个小问题。当首次呈现 selectInputs 时,它们被选择(样式和搜索能力)。但是,一旦用户单击按钮并且 selectInputs 和表格更新,selectInputs 就会失去其选定的样式。
如何在表格和 selectInputs 更新时保持选定的样式?
library(shiny)
library(DT)
# Selectize input ids
selectize_ids <- function(ids) {
tmp <- paste0(" $('#", ids, "')")
tmp <- paste0(tmp, ".selectize();")
c(
"function(settings){",
tmp,
"}"
)
}
shinyApp(
ui = fluidPage(
div(style = "display: none;", selectInput(inputId = "dummy", label = NULL, choices = 1:2)),
actionButton(inputId = "my_button", label = "Click Me"),
DT::dataTableOutput(outputId = "table")
),
server = function(input, output, session) {
input_ids <- c("A_1", "A_2")
df_reactive <- reactive({
data.frame(
A = sapply(input_ids, function(id) as.character(selectInput(
inputId = id,
label = NULL,
choices = paste0(c("a", "b", "c"), input$my_button)
)))
)
})
output$table <- DT::renderDataTable({
DT::datatable(
data = isolate(df_reactive()),
selection = "none",
rownames = F,
escape = F,
options = list(
initComplete = JS(selectize_ids(input_ids)),
preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')
)
)
})
proxy <- DT::dataTableProxy(outputId = "table")
observe({
DT::replaceData(proxy = proxy, data = df_reactive(), rownames = F)
})
}
)