问题
I am writing an R Shiny app. I use at DT datatable with specific colors for text entries. When the table is resorted the colors do not stay with their correct rows. Instead they stay in place.
I assume that I need to observe and react to the event of the table being reordered/filtered. How do I do that?
Sample code below.
library(shiny)
library(DT)
ui= shinyUI(fluidPage(
titlePanel("Test reorder DT datatave"),
sidebarLayout(
actionButton("button does nothing", "nothing")
,
mainPanel(
DT::dataTableOutput("mydt")
)
)
))
server <- function(input, output) {
output$mydt <- DT::renderDataTable({
dat <- data.frame(src=c(1,2,3), tgt=c("█", "█", "█"))
mycolors <- c("dodgerblue2", "grey", "firebrick2")
rgbcolors <- apply(grDevices::col2rgb(mycolors), 2,
function(rgb) sprintf("rgb(%s)", paste(rgb, collapse=",")))
column <- 2
jscode <- paste("function(row, data, index) {",
sprintf("var colors=%s;\n$(this.api().cell(index,
%s).node()).css('color', colors[index]);",
sprintf("[%s]", paste(sprintf("'%s'", rgbcolors),
collapse=", ")), column), "}", sep="\n")
datatable(dat, escape=FALSE,
options = list(rowCallback=JS(jscode))
)
})
}
shinyApp(ui = ui, server = server)
回答1:
Is it OK to set the colors directly in the tgt
column? Like this:
mycolors <- c("dodgerblue2", "grey", "firebrick2")
rgbcolors <- apply(grDevices::col2rgb(mycolors), 2,
function(rgb) sprintf("rgb(%s)", paste(rgb, collapse=",")))
tgt <- sprintf('<span style="color:%s">█</span>', rgbcolors)
dat <- data.frame(src=c(1,2,3), tgt=tgt)
datatable(dat, escape=FALSE)
来源:https://stackoverflow.com/questions/47740337/how-to-ensure-row-coloring-updates-when-r-shiny-dt-datatable-is-sorted-filtered