shinyjs:当条件未计算为 TRUE 时,切换不会隐藏自定义 UI

shinyjs: toggle doesn't hide custom UI when condition does not evaluate to TRUE

我正在玩 shinyjs pkg 和 hiding/showing 自定义 UI 的各种选项。在下面的应用程序中,我想显示选定的地块,如果未选择任何选项,则显示空 space。我使用 toggle(),只要至少选择了 checkboxGroupInput 中的一个选项,它就可以达到目的,但是当没有选择任何选项时,两个图都会显示。根据 documentation

If condition is given to toggle, that condition will be used to determine if to show or hide the element. The element will be shown if the condition evaluates to TRUE and hidden otherwise.

我是不是漏掉了什么明显的东西?

library(shiny)
library(shinyjs)
library(ggplot2)

ui <-dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    useShinyjs(),
    checkboxGroupInput(inputId = 'options',
                       label = 'Choose your plot(s)',
                       choices = list("Plot 1" = 1,
                                      "Plot2" = 2)),
                       #selected = 1:2),
    verbatimTextOutput('checkbox_text'),
        uiOutput("Ui1"),
        uiOutput('Ui2')
        )
)

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

  output$checkbox_text <- renderText({
    paste(input$options)
  })


    observe({
    shinyjs::toggle(id = "Ui1", condition = input$options == 1)
    shinyjs::toggle(id = "Ui2", condition = input$options == 2)
  })

  output$Ui1 <- renderUI({

    output$plot1 <- renderPlot({
      p <- ggplot(mtcars, aes(disp, mpg)) +
        geom_point() +
        geom_smooth() +
        ggtitle('Plot 1')
      p  
    })

    plotOutput('plot1')
  })

  output$Ui2 <- renderUI({

    output$plot2 <- renderPlot({
      p<- ggplot(mtcars, aes(disp, mpg, colour = as.factor(cyl))) +
        geom_point() +
        ggtitle('Plot 2')
      p
    })

    plotOutput('plot2')
  })

}

shinyApp(ui, server)

当您查找 checkboxGroupInput 中选中了哪些框时,通常最好评估您感兴趣的值是否等于 checkboxGroupInput 中的任何值 -用这个替换你的 observe 语句将解决问题:

  observe({
    shinyjs::toggle(id = "Ui1", condition = {1 %in% input$options})
    shinyjs::toggle(id = "Ui2", condition = {2 %in% input$options})
  })

就是说,我不确定为什么在您的情况下两个框都未选中会评估为 TRUE