1

我想访问传递给闪亮模块 UI 组件和模块callModule内部相应服务器组件的 id。我的意图是使用用户提供的 id 为弹出模式添加标题。

library(shiny)

fooModuleUI <- function(id) {
  ns <- NS(id)

  list(
    actionButton(inputId = ns("show"), label = "Show")
  )
}


fooModule <- function(input, output, session) {
  # I want to be able to access the id of the module here so that I can use it
  # to construct the title to the modal
  observeEvent(input$show, {
    showModal(
      modalDialog(
        title = paste0("Add ", "Module id here"), # Want module id here
        footer =
          div(
            modalButton("Cancel"),
            actionButton("insert", "Save")
          )
      )
    )
  })

}


ui <- shiny::fluidPage(
  fooModuleUI("test")
)

server <- function(input, output, session) {
  callModule(fooModule, "test")
}

shiny::shinyApp(ui, server)
4

1 回答 1

2

这有点像 hack 使用session$ns(通常用于创建模块输出等)。使用它,您可以创建示例 ID 并从中提取模块 ID。

fooModule <- function(input, output, session) {
  x <- session$ns('tmp')  # make an ID string
  mod_id <- substr(x, 1, nchar(x)-4)  # remove last 3 characters, ie "-tmp"

  observeEvent(input$show, {
    showModal(
      modalDialog(
        title = paste0("Add ", mod_id), # Want module id here
        footer =
          div(
            modalButton("Cancel"),
            actionButton("insert", "Save")
          )
      )
    )
  })
}

更简洁的方法是在调用时将模块 ID 作为额外参数传递callModule,如下所示:

fooModule <- function(input, output, session, mod_id) {
  observeEvent(input$show, {
    showModal(
      modalDialog(
        title = paste0("Add ", mod_id), # Want module id here
        footer =
          div(
            modalButton("Cancel"),
            actionButton("insert", "Save")
          )
      )
    )
  })
}
server <- function(input, output, session) {
  callModule(fooModule, "test", mod_id='test')
}
于 2019-11-06T20:58:41.833 回答