在模块服务器功能内访问闪亮的模块ID

时间:2019-11-06 18:51:27

标签: r shiny shinymodules

我想访问传递给闪亮的模块UI组件的ID和该模块的相应服务器组件内部的callModule。我的意图是使用用户提供的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)

1 个答案:

答案 0 :(得分:1)

这是使用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")
          )
      )
    )
  })
}

一种更清洁的方法是在调用callModule时将模块ID作为附加参数传递,如下所示:

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')
}