使用insertUI具有动态bs_accordion_sidebar()的闪亮应用

时间:2020-01-30 15:47:12

标签: dynamic shiny

我正在尝试构建一个动态的Shiny应用程序,该应用程序可在bs_accordion_sidebar中插入滑块。

“添加”按钮运行良好,但是我不知道应该在“删除”按钮代码中添加什么以更新条形图?

此外,当单击面板标题时,我认为它应该折叠并更改其颜色,但是什么也没发生?

感谢您的帮助!

databaseName.cblite2

1 个答案:

答案 0 :(得分:0)

我在这里找到了答案:https://stackoverflow.com/a/51517902/12812645 有必要取消由removeUI删除的输入

这是使用Shinyjs的更正代码:

library(shiny)
library(bsplus)
library(shinyjs)

# global button counter 
cpt <- 0

# function to create a new slider input
newinput <- function(ID, tag){ 

  div(id=ID,
      bs_append(
        tag = tag,
        title_side = ID,
        content_side = NULL,
        content_main = sliderInput( inputId = paste0("slider_",ID),
                                    label = paste0("slider_",ID),
                                    value = 0,
                                    min=0,
                                    max=10)
      )
  )

}

# UI
ui <- shinyUI(fluidPage(

  titlePanel("bs_append and insertUI"),

  sidebarPanel(

    fluidRow(
      actionButton("add", "+"),
      mytag <- bs_accordion_sidebar(id = "accordion",
                                     spec_side = c(width = 4, offset = 0),
                                     spec_main = c(width = 8, offset = 0)),
      div(id = "placeholder"),
      actionButton("delete", "-")
    )
  ),

  mainPanel(
    plotOutput('show_inputs')
  ),

  useShinyjs(debug = TRUE),
  use_bs_accordion_sidebar() 

))

# SERVER
server <- shinyServer(function(input, output) {

  # reactive function to collect all input values
  AllInputs <- reactive({
    myvalues <- sapply(names(input)[!names(input) %in% c("add", "delete")], function(x) input[[x]])
    myvalues <- unlist(myvalues[!unlist(lapply(myvalues, is.null))])
    print(myvalues)
    return(myvalues)
  })

  # simple output barplot 
  output$show_inputs <- renderPlot({
    barplot(AllInputs())
  })

  # take a dependency on 'add' button
  observeEvent(input$add, {

    cpt <<- cpt + 1 

    insertUI(
      selector ='#placeholder',
      where = "beforeEnd",
      ui = newinput(ID = cpt, 
                    tag = mytag)
    )

  })

  # take a dependency on 'delete' button
  observeEvent(input$delete, {

    removeUI(selector = paste0('#', cpt))
    runjs(paste0('Shiny.onInputChange("slider_',cpt,'", null)'))
    cpt <<- cpt - 1

  })

})


shinyApp(ui, server)