【问题标题】:Pass shiny widget initial values from server从服务器传递闪亮的小部件初始值
【发布时间】:2017-09-07 20:16:14
【问题描述】:

要启用应用程序特定状态的共享,我想根据提供的 URL 哈希设置小部件初始 selected 值。我只是不知道如何在初始化阶段传递哈希值。这说明:

library(shiny); library(shinyjs)

urlCode = "shinyjs.pageURL = function(params){ if(params[0] != ''){location.href = location.origin + '/#' + params[0];}}"

server = function(input, output, session) {
  observeEvent(session$clientData$url_hash, {
    hash = substr(session$clientData$url_hash, 2,10)
    # I need to pass hash to selectInput selected value
    # and pass `toupper(hash)` to tabsetPanel selected value
  })

  observeEvent(input$txt, {
    js$pageURL(input$txt) # appends tab choice to URL as hash
  })
}

ui = fluidPage(
  useShinyjs(),
  extendShinyjs(text = urlCode),
  selectInput("txt", "tab choice:", c("one", "two", "three"), selected = 'two'), # to be initialised as hash value

  # tab menu
  tabsetPanel(id = 'tab_menu', selected = 'TWO',  # to be initialised as hash value
              tabPanel("ONE",   textInput('txt_one', 'one text', '')),
              tabPanel("TWO",   textInput('txt_two', 'two text', '')),
              tabPanel("THREE", textInput('txt_three', 'three text', ''))
  )
)

shinyApp(ui = ui, server = server, options = list(launch.browser=T))

值当前初始化为“二”(selectInput)和“二”(tabsetPanel),但在 URL 调用为例如http://domain/#three(相对于根 http://domain/)。感谢任何指点。

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    您必须删除"#" 并使用update* 函数,如下所示:

    library(shiny)
    
    server <- function(input, output, session) {
    
      observe({
        hash <- gsub(pattern = "#", replacement = "", x = session$clientData$url_hash)
        updateTabsetPanel(session = session, inputId = "tab_menu", selected = toupper(hash))
        updateSelectInput(session = session, inputId = "txt", selected = hash)
      })
    }
    
    ui <- fluidPage(
    
      selectInput("txt", "tab choice:", c("one", "two", "three"), selected = 'two'), # to be initialised as hash value
    
      # tab menu
      tabsetPanel(
        id = 'tab_menu', selected = 'TWO',  # to be initialised as hash value
        tabPanel("ONE",   textInput('txt_one', 'one text', '')),
        tabPanel("TWO",   textInput('txt_two', 'two text', '')),
        tabPanel("THREE", textInput('txt_three', 'three text', ''))
      )
    )
    
    shinyApp(ui = ui, server = server)
    

    【讨论】:

    • 这看起来很棒。我刚刚知道这会将小部件选择永久绑定到 URL,而不仅仅是在初始化阶段。有没有办法将其限制为初始化?我想知道如果系统收到 2 条打开选项卡的指令,我是否会遇到 observe 触发器的问题 - 通过用户单击它,然后更新的 URL 触发重复指令..?
    • 是的,你是对的,观察者将被执行多次(指令将是相同的,因为您在单击选项卡时更新了 url,所以不是真正的问题)。您可以将observeEventonce = TRUE 一起使用,观察者将在初始化阶段只运行一次。我已经评论了你的要点。
    • 非常感谢维克多 :)
    猜你喜欢
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    • 2021-01-09
    • 2020-11-28
    • 2016-12-28
    • 2017-03-29
    • 1970-01-01
    • 2021-11-07
    相关资源
    最近更新 更多