不需要时,在R Shiny中禁用selectInput

时间:2017-07-12 14:39:12

标签: r shiny

我正在构建一个shiny网页,其中一个表单由两个selectInput组成:第一个 - 静态 - 位于ui部分,第二个 - 动态 - 位于server部分。实际问题的简化如下所示。

require(shiny)

ui <- fluidPage(

    # The static input
    selectInput(inputId = 'static',
                label = 'Make a choice',
                choices = c('A', 'B', 'C'),
                selectize = FALSE),

    # The dynamic input
    uiOutput(outputId = 'dynamicInput'),

    # The output
    hr(),
    strong('This is a check for the output:'),
    textOutput(outputId = 'check')

)

server <- function(input, output, session) {

    # The dynamic input definition
    output$dynamicInput <- renderUI({

        # This input exists if the `static`
        # one is equal to `A` only
        if (input$static == 'A') {
            selectInput(inputId = 'dynamic',
                        label = 'Choose a subset for `A`',
                        choices = c('A1', 'A2', 'A3'),
                        selectize = FALSE)
        } else {
            return(NULL)
        }

   })

   # The example output
   output$check <- renderText({

       paste(input$static, input$dynamic)

   })

}

shinyApp(ui, server)

在实际情况中,我必须基于静态输入在数据库上启动查询,最终是动态查询(如果存在)。

在测试应用时,我在第一轮中正确获得了动态selectInput,我可以选择 - 允许&#39;说 - A2选项。然后,如果我在静态B中选择selectInput,则动态输入不会响应,仍会显示之前的选择,而不是显示NULL

如果静态selectInput不等于A,我如何强制重置动态shinyjs?我是否必须使用Dean Attali&#39; s terraform apply之类的技巧手动隐藏

1 个答案:

答案 0 :(得分:5)

试试这个。它是使用反应值和观察的组合。

require(shiny)

ui <- fluidPage(

  # The static input
  selectInput(inputId = 'static',
              label = 'Make a choice',
              choices = c('A', 'B', 'C'),
              selectize = FALSE),

  # The dynamic input
  uiOutput(outputId = 'dynamicInput'),

  # The output
  hr(),
  strong('This is a check for the output:'),
  textOutput(outputId = 'check')

)

server <- function(input, output, session) {

  ## list to store reactive values
  values <- reactiveValues()


  # The dynamic input definition
  output$dynamicInput <- renderUI({

    # This input exists if the `static`
    # one is equal to `A` only
    if (input$static == 'A') {
      selectInput(inputId = 'dynamic',
                  label = 'Choose a subset for `A`',
                  choices = c('A1', 'A2', 'A3'),
                  selectize = FALSE)
    } else {
      return(NULL)
    }

  })

  ## this bit fixes the issue
  observe({
    if (input$static == "A") {
      values$dyn <- input$dynamic
    } else {
      values$dyn <- NULL
    }
  })

  # The example output
  output$check <- renderText({

    paste(input$static, values$dyn)

  })

}

shinyApp(ui, server)