R Shiny: Use navbarPage with bsModal by shinyBS

2019-07-22 17:42发布

问题:

I'm trying to add a tabPanel in navbarPage so that when you click on it opens a modal window instead of a new tab. The snippet below is not valid because tabPanel does not have an id parameter.

library(shiny)
library(shinyBS)
shinyUI(fluidPage(
    navbarPage("Sample App", id = "main_menu", 
        tabPanel("Open Modal", id = "moda")),
    bsModal("modal1", "Example", "moda", p("This is a modal"))
)

If I edit the generated HTML code from browser, I can make this possible by changing the line

<a href="#tab-9741-5" data-toggle="tab" data-value="Open Modal">Open Modal</a>

with

<a href="#" data-toggle="modal" data-target="#modal1">Open Modal</a>

on the <li> element.

Any idea how to do this or at least how can I override the generated html from shiny?

回答1:

One solution is to use Javascript to rewrite the attribute for the tab title. The JS code below finds the tab title link, and rewrites its attributes.

library(shiny)

jsStr <- '$(document).ready(function(){
  $("a[data-value=\'OpenModal\']").attr({
    "href":"#", 
    "data-toggle":"modal",
    "data-target":"#modal1"
  });
})
' 

ui <- shinyUI(fluidPage(
  tags$head(tags$script(HTML(jsStr))),
  navbarPage("title",
    tabPanel("OpenModal")
  ),
  bsModal("modal1", "Example", "moda", p("This is a modal"))
))


标签: r shiny shinybs