问题
I'm trying to manually expand a submenu in a sidebar in shiny dashboard. The updateTabItems
function only works with normal menus, but not with nested menus.
Here is basic example (modified from the updateTabItems
documentation) to show the problem. If I clicked on 'Switch tab', it switches the menus, but it doesn't expand the first menu that has a submenu. It seems that it only selected the submenu but doesn't expand the tree.
library(shiny)
library(shinydashboard)
ui <- dashboardPage(
dashboardHeader(title = "Simple tabs"),
dashboardSidebar(
sidebarMenu(
id = "tabs",
menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard"),
menuSubItem("Sub Menu 1",icon = icon("folder-open"), tabName = "subMenu1")
),
menuItem("Widgets", tabName = "widgets", icon = icon("th"))
),
actionButton('switchtab', 'Switch tab')
),
dashboardBody(
tabItems(
tabItem(tabName = "dashboard",
h2("Dashboard tab content")
),
tabItem(tabName = "widgets",
h2("Widgets tab content")
)
)
)
)
server <- function(input, output, session) {
observeEvent(input$switchtab, {
newtab <- switch(input$tabs,
"subMenu1" = "widgets",
"widgets" = "subMenu1"
)
updateTabItems(session, "tabs", newtab)
})
}
shinyApp(ui, server)
}
I would like manually expand the tree, select the menu and the submenu. Any suggestions are welcome. Thanks.
Update:
A working code with the complete solution is in Shiny expanding submenu items manually
回答1:
I helped myself out defining some JavaScript, using the JavaScript interface extendShinyjs
in shiny:
js$selectMenuItem(0)
js$selectMenuSubItem(2)
useShinyjs(),
extendShinyjs(text = jsSelectMenuItem),
extendShinyjs(text = jsSelectMenuSubItem)
select menuItem i
jsSelectMenuItem <- "shinyjs.selectMenuItem = function(i){
setTimeout(function(){
$('.treeview > a').eq(i).click();
}, 200);
}"
select menuSubItem i
jsSelectMenuSubItem <- "shinyjs.selectMenuSubItem = function(i){
setTimeout(function(){
$('.treeview-menu > li > a').eq(i).click();
}, 800);
}"
来源:https://stackoverflow.com/questions/32465177/how-to-manually-expand-a-submenu-in-a-shiny-dashboard-side-bar