using modal window in Shiny module

There is a modalButton() function in shiny designed to do exactly this. You do not need to worry about any namespace issues if you use this. Here is the documentation. And here it is in action.

library(shiny)

# Modal module UI
modalModuleUI <- function(id) {
  ns <- NS(id)
  actionButton(ns("openModalBtn"), "Open Modal")
}

# Modal module server
modalModule <- function(input, output, session) {

  myModal <- function() {
    modalDialog(
      footer = modalButton("Close Modal")
    )
  }
  # Show modal dialog on start up
  observeEvent(input$openModalBtn,
               ignoreNULL = TRUE,
               showModal(myModal())
  )
}

# Main app UI
ui <- fluidPage(modalModuleUI("foo"))

# Main app server
server <- function(input, output, session) {
  callModule(modalModule, "foo")
}

shinyApp(ui, server)

I figured it out myself after re-reading this more carefully. Like with renderUI the id elements in the modal need to be wrapped in ns() to make them available in the module namespace. The namespace has to be loaded inside the modal explicitly using ns <- session$ns, like this:

library(shiny)

# Modal module UI
modalModuleUI <- function(id) {
  ns <- NS(id)
  actionButton(ns("openModalBtn"), "Open Modal")
}

# Modal module server
modalModule <- function(input, output, session) {

  myModal <- function() {
    ns <- session$ns
    modalDialog(actionButton(ns("closeModalBtn"), "Close Modal"))
  }

  # open modal on button click
  observeEvent(input$openModalBtn,
               ignoreNULL = FALSE,   # Show modal on start up
               showModal(myModal())
  )

  # close modal on button click
  observeEvent(input$closeModalBtn, { 
    removeModal() 
  })
}

# Main app UI
ui <- fluidPage(modalModuleUI("foo"))

# Main app server
server <- function(input, output, session) {
  callModule(modalModule, "foo")
}

shinyApp(ui, server)

Note: If the myModal function is defined outside the module server function, one has to pass session when calling it, i.e. showModal(myModal(session)) and myModal <- function(session) {...}.

I have updated the example app so that it works now and added a textInput too.