问题
I'm trying to make a shiny module that will alter a datatable based on a custom searchbar.
I managed to make an app that will print the results of a searchbar search into R-Studio console, but, how do I return the results from the module and update the reactive data storage?
Here is an example app, I want to return what is printed to update the reactive:
myModuleUI <- function(id) {
ns <- NS(id)
tagList(
fluidRow(
column(width=2,
textInput(ns("searchField"), "Search"),
dataTableOutput("table")
)
)
)
}
myModule <- function(input, output, session, df) {
observeEvent(input$searchField, {
if(!is.null(input$searchField)){
print(
df %>% filter_at(vars(names(df)), any_vars(str_detect(as.character(.), input$searchField)))
)
}
})
}
# Use the module in an application
ui <- fluidPage(
myModuleUI("myModule1")
)
server <- function(input, output, session) {
out <- reactiveValues(
df = data.frame(
company = c('a', 'b', 'c', 'd'),
bond = c(0.2, 1, 0.3, 0),
equity = c(0.7, 0, 0.5, 1),
cash = c(0.1, 0, 0.2, 0),
stringsAsFactors = FALSE
)
)
callModule(myModule, "myModule1", df = out$df)
output$table <- DT::renderDataTable({
m <- datatable(
out$df,
options = list(dom = 'tip')
)
})
}
shinyApp(ui, server)
回答1:
You have to use ns()
on datatableOutput outputId too, so you can use it within the module:
myModuleUI <- function(id) {
ns <- NS(id)
tagList(
fluidRow(
column(width=2,
textInput(ns("searchField"), "Search"),
dataTableOutput(ns("table"))
)
)
)
}
myModule <- function(input, output, session, df) {
output$table <- DT::renderDataTable({
datatable(
if(!is.null(input$searchField)){
df %>% filter_at(vars(names(df)), any_vars(str_detect(as.character(.), input$searchField)))
} else df,
options = list(dom = 'tip')
)
})
}
# Use the module in an application
ui <- fluidPage(
myModuleUI("myModule1")
)
server <- function(input, output, session) {
out <- reactiveValues(
df = data.frame(
company = c('a', 'b', 'c', 'd'),
bond = c(0.2, 1, 0.3, 0),
equity = c(0.7, 0, 0.5, 1),
cash = c(0.1, 0, 0.2, 0),
stringsAsFactors = FALSE
)
)
callModule(myModule, "myModule1", df = out$df)
}
shinyApp(ui, server)
来源:https://stackoverflow.com/questions/64812459/search-bar-module-in-r-shiny-how-to-return-results