将输入$ value传递给闪亮数据表中的JS()语句

时间:2016-01-25 20:48:08

标签: r shiny dt

使用此代码格式化数据表中的行

 rowCallback = DT::JS(
      'function(row, data) {
        // Bold cells for those >= 5 in the first column
        if (parseFloat(data[0]) >= 5.0)
          $("td", row).css("background", "red");
      }'
    )

我想更改此代码,以便突出显示基于输入$值,而不是静态“5.0”值。这样用户就可以点击图表上的某个点,具有该值的行将在数据表中突出显示。

但替换输入$ click for 5似乎不起作用。想法?

rowCallback = DT::JS(
          'function(row, data) {
            // Bold cells for those >= 5 in the first column
            if (parseFloat(data[0]) >= input$click)
              $("td", row).css("background", "red");
          }'
        )

1 个答案:

答案 0 :(得分:1)

使用最新版本的DT,您可以在不使用formatStyle的任何Javascript的情况下执行此操作。

以下是一个例子:

library(shiny)
library(DT)
shinyApp(
        ui = fluidPage(numericInput("cutoff", "Test", 5, min = 0, max = 10, step = 1),
                       DT::dataTableOutput('tbl')
        ),
        server = function(input, output) {
                output$tbl = DT::renderDataTable(
                        datatable(iris, options = list(lengthChange = FALSE)) %>% formatStyle(
                                'Sepal.Length',
                                target = 'row',
                                backgroundColor = styleInterval(input$cutoff, c('gray', 'yellow'))
                        )
                )
        }
)

更多信息和示例herehere

您可能需要运行以下命令来安装DT的开发版本:

devtools::install_github('rstudio/DT')

如果你不能使用DT的开发版,这是另一个解决方案:

library(shiny)
library(DT)
shinyApp(
        ui = fluidPage(numericInput("cutoff", "Test", 5, min = 0, max = 10, step = 1),
                       uiOutput("tbl_holder")

        ),
        server = function(input, output) {
                output$tbl_holder <- renderUI({
                        DT::dataTableOutput('tbl')
                })

                output$tbl = DT::renderDataTable(
                        datatable(iris, options = list(lengthChange = FALSE,rowCallback = DT::JS(
                                paste0('function(row, data) {
                                // Bold cells for those >= 5 in the first column
                                if (parseFloat(data[0]) >=',input$cutoff,')
                                $("td", row).css("background", "red");
        }')
        )))) 
        }
)

您可以使用paste在JS函数和renderUi / uiOutput中添加截止值,以便每次截止值更改时更新打印数据表的函数。