闪亮添加并删除至收藏夹

时间:2019-06-23 00:56:55

标签: r shiny

在进行this问答之后,我对扩展很感兴趣。我希望能够从收藏夹列表中添加和删除项目。我可以整理一下如何执行此操作,但是无法执行。

我认为需要:

  1. 不在收藏夹列表中时的“添加到收藏夹按钮”
  2. 收藏夹列表中的“从收藏夹中删除按钮”
  3. 我认为收藏夹需要有反应性
  4. 不喜欢的人需要有反应性

对吗?我可以展示我尝试过的内容,但不确定是否有帮助...

date-fns

1 个答案:

答案 0 :(得分:1)

假设您想将现有选项添加到“收藏夹”列表中,则以下几行可能会有所帮助:

library(shiny)
library(shinyWidgets)

ALL.options <- apply(expand.grid(LETTERS, LETTERS), 1, function(x){paste(x, collapse="")})
favourites <- sample(ALL.options, 20)

ui <- fluidPage(

    h3("Favourites:"),
    radioGroupButtons(inputId = "radio", 
        choices = sort(favourites), 
        individual = TRUE, 
        selected = character(0),
        width="20%"),

    ## select to remove from favourites
    selectInput(inputId = "selectRemove", label = "Remove from favourites", 
        choices = c("", sort(favourites)), 
        selected = ""
    ),

    actionButton(inputId = "remove", label = "Remove from favourites"),

    tags$hr(),

    selectInput(inputId="select", label = "Other options",
        choices = c("", ALL.options),
        selected = ""
    ),  

    ## select to add to favourites
    selectInput(inputId = "selectAdd", label = "Add to favourites", 
        choices = c("", ALL.options),
        selected = ""

    ),

    actionButton(inputId = "add", label = "Add to favourites"),

    tags$hr(),

    h3("THIS IS YOUR SELECTION:"),

    verbatimTextOutput("choice")

)

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

  ## initialize current states as reactive values
  currentStates <- reactiveValues(
      selected = NULL,
      favourites = sort(favourites)
  )

  observeEvent(input$add, {

        req(input$selectAdd)

        ## add to favourites
        currentStates$favourites <- union(currentStates$favourites, input$selectAdd)

      })

  observeEvent(input$remove, {

        req(input$selectRemove)

        ## remove from favourites
        currentStates$favourites <- setdiff(currentStates$favourites, input$selectRemove)

      })

  observeEvent(currentStates$favourites, ignoreInit = TRUE, {

        req(currentStates$favourites)

        ## update favourites list
        updateRadioGroupButtons(session,
            inputId = "radio",
            choices = sort(currentStates$favourites)
        )

        ## update remove from favourites list
        updateSelectInput(session,
            inputId = "selectRemove",
            choices = c("", sort(currentStates$favourites)),
            selected = ""
        )

      })

  ## update based on radioGroupButtons
  observeEvent(input$radio, {

        currentStates$selected <- input$radio

      })

  ## update based on selectInput
  observeEvent(input$select, {

        currentStates$selected <- input$select

      })

  output$choice <- renderPrint({

        validate(need(currentStates$selected, "None selected"))

        currentStates$selected

      })

}

shinyApp(ui, server)