render html file with script in react app - html

I have a html file with script tag and some link into it.
when i render it with html file it bring the result i mean a chart but when i render it in react js app wiht dangerouslySetInnerHTML it does not render and does not bring my chart.
this is my html code that i take it from backend(api)
const html = `<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0" />
<link
href="somelink"
rel="stylesheet"
/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div class="app-chart-container">
<canvas class="app-charts" id="line-chart-40197" dir="ltr"></canvas>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script>
$(document).ready(function () {
$("[data-toggle='tooltip']").tooltip({ placement: "right" });
});
var ctx = document.getElementById("line-chart-40197");
if (ctx) {
ctx.height = 300;
var myChart = new Chart(ctx, {
type: "line",
data: {
labels: [
"92/3",
"92/6",
"92/9",
"92/12",
"93/3",
"93/6",
"93/9",
"93/12",
"94/3",
"94/6",
"94/9",
"94/12",
"95/3",
"95/6",
"95/9",
"95/12",
"96/3",
"96/6",
"96/9",
"96/12",
"97/3",
"97/6",
"97/9",
"97/12",
"98/3",
"98/6",
"98/9",
"98/12",
"99/3",
"99/6",
],
type: "line",
defaultFontFamily: "VazirFD",
datasets: [
{
label: "شرکت",
data: [
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"-262",
"-262",
"-262",
"-262",
"66793",
"70787",
"122463",
"591087",
"591088",
"597421",
"600635",
"614257",
"1304086",
"1320727",
"1352606",
"2830629",
"3016812",
"3042351",
"3126253",
],
backgroundColor: "transparent",
borderColor: "#9d0606",
borderWidth: 2,
pointStyle: "circle",
pointRadius: 3,
pointBorderColor: "transparent",
pointBackgroundColor: "#9d0606",
type: "line",
},
],
},
options: {
responsive: true,
tooltips: {
mode: "index",
titleFontSize: 12,
titleFontColor: "#000",
bodyFontColor: "#000",
backgroundColor: "#fff",
defaultFontFamily: "VazirFD",
titleFontFamily: "VazirFD",
bodyFontFamily: "VazirFD",
cornerRadius: 3,
intersect: true,
callbacks: {
label: function (tooltipItem, data) {
return (
data.datasets[tooltipItem.datasetIndex].label +
" : " +
tooltipItem.yLabel
.toString()
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
);
},
},
},
legend: {
display: true,
rtl: true,
labels: {
usePointStyle: true,
fontFamily: "VazirFD",
},
},
scales: {
xAxes: [
{
stacked: false,
display: true,
gridLines: {
display: true,
drawBorder: false,
},
scaleLabel: {
display: true,
labelString: "سال مالی",
fontFamily: "VazirFD",
},
ticks: {
fontFamily: "VazirFD",
fontColor: "#9aa0ac",
minRotation: 90,
callback: function (value, index, values) {
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
},
},
},
],
yAxes: [
{
stacked: false,
display: true,
gridLines: {
display: true,
drawBorder: false,
},
scaleLabel: {
display: false,
labelString: "میلیون ریال",
fontFamily: "VazirFD",
},
ticks: {
margin: 20,
fontFamily: "VazirFD",
fontColor: "#9aa0ac",
minRotation: 0,
callback: function (value, index, values) {
var processValue = value;
if (value >= 1000 && value < 1000000) {
processValue = value / 1e3 + "K";
} else if (value >= 1000000 && value < 1000000000) {
processValue = value / 1e6 + "M";
} else if (value >= 1000000000) {
processValue = value / 1e9 + "B";
} else if (value < 0 && value <= -1000 && value > -1000000) {
processValue = value / 1e3 + "K";
} else if (
value < 0 &&
value <= -1000000 &&
value > -1000000000
) {
processValue = value / 1e6 + "M";
} else if (value < 0 && value <= -1000000000) {
processValue = value / 1e9 + "B";
}
return processValue
.toString()
.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
},
},
},
],
},
title: {
display: true,
text: "روند سودآوری TTM (میلیون ریال)",
fontFamily: "VazirFD",
},
},
});
}
</script>
this is my html file.
but i have a problem with render of that with react
when I compile this file with
this is my react component that i want to render that html code (my html code has some script tag )
import React from "react";
export default function Dashboard() {
return (
<div dangerouslySetInnerHTML={{__html: html }} />
)
}
i dont get my html file correctly.
and react does not render it.
when i open this file into .html file it works but in react does not render any thing.
how can i render this file in react please help me

I had to do this recently because an API I was consuming returns HTML content. You can use a library like html-to-react to parse the HTML for you and convert it to a React component that you can then use inside your React application. In my case, I created a component so that I can reuse this logic anywhere I need to display HTML content.
import { useMemo } from 'react';
import { Parser } from 'html-to-react';
const HTMLContent = (props) => {
const htmlToReactParser = useMemo(() => new Parser(), []);
const parsedHTML = htmlToReactParser.parse(props.html);
return <div className={styles['blog-html-content']}>{parsedHTML}</div>;
};

Related

Google charts - data from local json file - custom tooltips

I'm using google charts to create dvb-c channels availability charts. The data for charts is red from local json file. The charts are working really fine, but I would like to add one feature to it, but I need some assistanse with it.
The feature I would like to add is custom tooltips, but I have no idea how to do it. I know I have to add the wanted data to json, but like I said Im not sure how to do it and how do I have to change my html code to make it work. I want tooltip to read local html file and show the content on tooltip.
Here is my html code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<div id="chart" style="width:3000px; height:600px;"></div>
</body>
<script>
// Visualization API with the 'corechart' package.
google.charts.load('visualization', { packages: ['corechart'] });
google.charts.setOnLoadCallback(drawLineChart);
function drawLineChart() {
$.ajax({
url: "./avail.json",
dataType: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
var channels = [['Channel', 'HKI (%)', 'LTI (%)']]; // Define an array and assign columns for the chart.
// Loop through each data and populate the array.
$.each(data, function (index, value) {
channels.push([value.Channel, value.HKI, value.LTI]);
});
// Set chart Options.
var options = {
title: 'DVB-C Availability (HKI & LTI)',
series: {
0: { color: '#ff3385', lineWidth: 5, pointSize: 5 },
1: { color: '#000000', lineWidth: 1, pointSize: 3},
},
vAxis: { "title": "Availability (%)", maxValue: 100 },
hAxis : { "title": "Channels", showTextEvery:1, textStyle : {fontSize: 8, bold:'true' }, slantedText:true, slantedTextAngle:45 },
chartArea:{left:70,top:50,right:40,width:"90%",height:"70%"},
tooltip: {isHtml: true, trigger: 'both'},
legend: { position: 'top', textStyle: { color: '#555', fontSize: 14} }
};
// Create DataTable and add the array to it.
var figures = google.visualization.arrayToDataTable(channels)
// Define the chart type (LineChart) and the container (a DIV in our case).
var chart = new google.visualization.LineChart(document.getElementById('chart'));
chart.draw(figures, options); // Draw the chart with Options.
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Got an Error');
}
});
}
</script>
</html>
Here is little snippet of my current json file:
[
{ "Channel": "MTV Rocks", "HKI": 99.104700, "LTI": 98.760400 },
{ "Channel": "MTV3 HD", "HKI": 99.724600, "LTI": 99.724600 },
{ "Channel": "MTV3", "HKI": 100.000000, "LTI": 100.000000 },
]
Should I add something like this to json ?
[
{ "Channel": "MTV Rocks", "HKI": 99.104700, <object data="./hki1.html"></object> "LTI": 98.760400, <object data="./lti1.html"></object> },
{ "Channel": "MTV3 HD", "HKI": 99.724600, <object data="./hki1.html"></object>"LTI": 99.724600, <object data="./lti1.html"></object> },
{ "Channel": "MTV3", "HKI": 100.000000, object data="./hki1.html"></object>"LTI": 100.000000, object data="./lti1.html"></object> },
]
If this is the right way to change json, I have no idea how to change the html code to make this work.
Maybe someone can help me out with this ?
first, 'visualization' is not a valid version number for google charts.
it looks the this was left over from the old library loader code.
use 'current' instead...
google.charts.load('current', { packages: ['corechart'] });
next, you'll need to copy the html from the file into the json,
rather than trying to reference an external file.
the tooltip is only expecting an html snippet, not a full blown file.
to add the custom tooltip, first we need to add the column for the tooltip.
it should be an object, as follows...
{type: 'string', role: 'tooltip', p: {html: true}}
if you want a tooltip for both "HKI" & "LTI",
you need to add the above tooltip column after each column heading...
var channels = [['Channel', 'HKI (%)', {type: 'string', role: 'tooltip', p: {html: true}}, 'LTI (%)', {type: 'string', role: 'tooltip', p: {html: true}}]];
include the html when loading the rows...
$.each(data, function (index, value) {
channels.push([
value.Channel,
value.HKI,
'<div>custom html goes here</div>',
value.LTI,
'<div>custom html goes here</div>'
]);
});
see following working snippet for an example...
google.charts.load('current', { packages: ['corechart'] });
google.charts.setOnLoadCallback(drawLineChart);
function drawLineChart() {
var data = [
{ "Channel": "MTV Rocks", "HKI": 99.104700, "LTI": 98.760400 },
{ "Channel": "MTV3 HD", "HKI": 99.724600, "LTI": 99.724600 },
{ "Channel": "MTV3", "HKI": 100.000000, "LTI": 100.000000 },
];
var channels = [['Channel', 'HKI (%)', {type: 'string', role: 'tooltip', p: {html: true}}, 'LTI (%)', {type: 'string', role: 'tooltip', p: {html: true}}]];
// Loop through each data and populate the array.
$.each(data, function (index, value) {
channels.push([
value.Channel,
value.HKI,
'<div class="ggl-tooltip"><div>' + value.Channel + '</div><div>' + value.HKI + '</div></div>',
value.LTI,
'<div class="ggl-tooltip"><div>' + value.Channel + '</div><div>' + value.LTI + '</div></div>'
]);
});
// Set chart Options.
var options = {
title: 'DVB-C Availability (HKI & LTI)',
series: {
0: {color: '#ff3385', lineWidth: 5, pointSize: 5},
1: {color: '#000000', lineWidth: 1, pointSize: 3},
},
vAxis: {title: "Availability (%)", maxValue: 100},
hAxis : {title: "Channels", showTextEvery:1, textStyle : {fontSize: 8, bold:'true'}, slantedText:true, slantedTextAngle:45},
chartArea:{left: 70, top:50, right:40, width:"90%", height:"70%"},
tooltip: {isHtml: true, trigger: 'both'},
legend: {position: 'top', textStyle: { color: '#555', fontSize: 14}}
};
// Create DataTable and add the array to it.
var figures = google.visualization.arrayToDataTable(channels)
// Define the chart type (LineChart) and the container (a DIV in our case).
var chart = new google.visualization.LineChart(document.getElementById('chart'));
chart.draw(figures, options); // Draw the chart with Options.
}
.ggl-tooltip {
border: 1px solid #E0E0E0;
font-family: Arial, Helvetica;
font-size: 10pt;
padding: 12px 12px 12px 12px;
}
.ggl-tooltip div {
padding-top: 6px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>
EDIT
if you want to display an external html file as the tooltip,
it may make sense to hide the standard tooltip,
and display the external file 'onmouseover'
see following working snippet for an example...
google.charts.load('current', { packages: ['corechart'] });
google.charts.setOnLoadCallback(drawLineChart);
function drawLineChart() {
var data = [
{ "Channel": "MTV Rocks", "HKI": 99.104700, "LTI": 98.760400 },
{ "Channel": "MTV3 HD", "HKI": 99.724600, "LTI": 99.724600 },
{ "Channel": "MTV3", "HKI": 100.000000, "LTI": 100.000000 },
];
var channels = [['Channel', 'HKI (%)', 'LTI (%)']];
// Loop through each data and populate the array.
$.each(data, function (index, value) {
channels.push([
value.Channel,
value.HKI,
value.LTI
]);
});
// Set chart Options.
var options = {
title: 'DVB-C Availability (HKI & LTI)',
series: {
0: {color: '#ff3385', lineWidth: 5, pointSize: 5},
1: {color: '#000000', lineWidth: 1, pointSize: 3},
},
vAxis: {title: "Availability (%)", maxValue: 100},
hAxis : {title: "Channels", showTextEvery:1, textStyle : {fontSize: 8, bold:'true'}, slantedText:true, slantedTextAngle:45},
chartArea:{left: 70, top:50, right:40, width:"90%", height:"70%"},
tooltip: {trigger: 'none'},
legend: {position: 'top', textStyle: { color: '#555', fontSize: 14}}
};
// Create DataTable and add the array to it.
var figures = google.visualization.arrayToDataTable(channels)
// Define the chart type (LineChart) and the container (a DIV in our case).
var chart = new google.visualization.LineChart(document.getElementById('chart'));
var frame = document.getElementById('tooltip');
// hide external html on mouse out
google.visualization.events.addListener(chart, 'onmouseout', function () {
frame.className = 'hidden';
});
// display external html on mouse over
google.visualization.events.addListener(chart, 'onmouseover', function (props) {
if (props.row === null) {
return;
}
var chartLayout = chart.getChartLayoutInterface();
var bounds = chartLayout.getBoundingBox('point#' + (props.column - 1) + '#' + props.row);
frame.style.left = bounds.left + 'px';
frame.style.top = bounds.top + 'px';
// replace this
frame.src = 'https://www.december.com/html/demo/hello.html';
// with this
//frame.src = '../' + figures.getColumnLabel(props.column) + (props.row + 1) + '.html';
frame.className = 'tooltip';
});
chart.draw(figures, options);
}
.hidden {
display: none;
visibility: hidden;
}
.tooltip {
background-color: #ffffff;
position: absolute;
height: 200px;
width: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>
<iframe class="hidden" id="tooltip"></iframe>

Kendo spreadsheet is not binding first time using json

I have a kendo spread sheet which is not loading first time in browser after refreshing it will works. I already searched lots of in google but unable to find any solutions.Please help me how to fixed that issue. I am using asp.net mvc.
my spread sheet code is below
var customVal = $("#customInput").data("value");
var CellCount = $('#sessionDivCount').attr('data-id');
var headercount = '1';
var displayCount = Number(CellCount) + Number(headercount);
$(function () {
var shouldPopulateHeader = true;
var dataSource = new kendo.data.DataSource({
requestEnd: function (e) {
setTimeout(function (e) {
if (shouldPopulateHeader) {
shouldPopulateHeader = false;
var spreadsheet = $("#spreadsheet").data("kendoSpreadsheet");
var sheet = spreadsheet.activeSheet();
// Change the default headers for the first and the second column
sheet.batch(function () {
sheet.range("A1").value("Order ID");
sheet.range("D1").value("Check/Receipt/Reference/Confirmation Number");
sheet.range("E1").value("Date Check Was Made Made/Payment Was Maid");
sheet.range("F1").value("Agent Payment Confirmation");
sheet.range("G1").value("Estimated payment Arrival Date");
sheet.range("A1:A16384 ").enable(false);
sheet.range("A2:A16384 ").textAlign = "center";
sheet.range("B1:B16384 ").enable(false);
var range = sheet.range("A2:A16384"); // 2x2 cell range
range.bold = true;
range.textAlign = "center";
range.color("green");
var range1 = sheet.range("B2:B16384"); // 2x2 cell range
range1.bold = true;
range1
range1.textAlign = "center";
range1.color("black");
range1.defaultValue = null;
sheet.range("c2").textAlign = "center";
}, { recalc: true });
}
}, 0);
},
transport: {
read: onRead,
submit: onSubmit
},
batch: true,
change: function () {
$("#cancel, #save").toggleClass("k-state-disabled", !this.hasChanges());
},
schema: {
model: {
OrderID: "OrderID",
fields: {
OrderID: {
type: "number",
defaultValue: null
},
PO: {
type: "string",
defaultValue: null
},
Method: {
type: "string",
},
Check_Receipt_Refernce_confirmation_Number: {
type: "string"
},
DateCheck_Was_Mailed_Payment_Was_Made: {
type: "date"
},
Agent_Payment_Confirmation: {
type: "string"
},
Estimated_Payment_Arrival_Date: {
type: "date"
},
}
}
}
});
$("#spreadsheet").kendoSpreadsheet({
columns: 7,
rows: displayCount,
toolbar: true,
sheetsbar: false,
sheets: [{
name: "Products",
dataSource: dataSource,
rows: [{
height: 20,
cells: [
{
value: "Order ID",
bold: "true",
background: "#9c27b0",
textAlign: "center",
color: "white",
hidden: true,
enable: false
}, {
bold: "true",
background: "#9c27b0",
textAlign: "center",
color: "white",
enable: false
}, {
bold: "true",
background: "#9c27b0",
textAlign: "center",
color: "white",
enable: false
}, {
bold: "true",
background: "#9c27b0",
textAlign: "center",
color: "white",
enable: false
},
{
bold: "true",
background: "#9c27b0",
color: "white",
textAlign: "center",
enable: false
},
{
bold: "true",
background: "#9c27b0",
textAlign: "center",
color: "white"
}, {
bold: "true",
background: "#9c27b0",
textAlign: "center",
color: "white"
}
]
}],
columns: [
{ width: 145 },
{ width: 145 },
{ width: 145 },
{ width: 300 },
{ width: 300 },
{ width: 300 },
{ width: 300 }
]
}]
});
function onSubmit(e) {
var arrofId = new Array();
var models = {};
var obj = "";
for (i = 0; i < JSON.stringify(e.data.created.length); i++) {
obj = e.data.created[i];
arrofId.push(obj);
}
arrofId.push(obj);
$.ajax({
type: "POST",
url: "/Agent/GetDataSpreadSheetSubmit1",
data: '{models: ' + JSON.stringify(arrofId) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('Record Saved Succesfully');
$('#grid').data('kendoGrid').dataSource.read();
$('#grid').data('kendoGrid').refresh();
},
error: function (xhr, httpStatusMessage, customErrorMessage) {
alert(xhr.responseText);
}
});
}
function onRead(options) {
$.ajax({
url: "../Agent/GetDataSpreadSheet",
type: "get",
dataType: "json",
success: function (result) {
debugger
options.success(result.data);
$("#spreadsheet").data("kendoSpreadsheet").refresh();
},
error: function (result) {
options.error(result);
}
});
}
$("#save").click(function () {
debugger
if (!$(this).hasClass("k-state-disabled")) {
dataSource.sync();
}
});
$("#cancel").click(function () {
if (!$(this).hasClass("k-state-disabled")) {
dataSource.cancelChanges();
}
});
});
}
any my controller action method for getting the list is below
[HttpGet]
public ActionResult GetDataSpreadSheet()
{
int statusID = 50;
var list = agentLogic.GetListByStatusID_forSpreadSheet(statusID).OrderBy(p => p.OrderID).ThenBy(o => o.OrderID);
HttpContext.Session["CheckSpreadsheetCount"] = list.Count();
return Json(new { total = list.Count(), data = list }, JsonRequestBehavior.AllowGet);
}
kendo spread sheet is not loading first time but after reload the browser its works as expected. Please help me what should i do? Please help me i am still unable to find any solution when it loads first time in any browser it creates problem after refresh it's working as expected.

highchart csv export in gauge option gives first calumn with value 0

var gaugeOptions = {
chart: {
type: 'solidgauge'
},
title: null,
pane: {
center: ['50%', '85%'],
size: '140%',
startAngle: -90,
endAngle: 90,
background: {
backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || '#FADCB5',
innerRadius: '60%',
outerRadius: '100%',
shape: 'arc'
}
},
exporting: {
csv:{
columnHeaderFormatter:function(item, key, series){
if(key === 'y'){
return 'Total Stock (%)';
}else if(key === '' || key === undefined){
return 'Micromarket';
}
}
},
buttons:{
contextButton:{
menuItems: [{
textKey: 'downloadCSV',
onclick: function (){
this.downloadCSV();
}
}]
}
}
},
tooltip: {
enabled: false
},
// the value axis
yAxis: {
stops: [
[0.1, '#F2A23C'], // orange
[0.5, '#F2A23C'],
[0.9, '#F2A23C']
],
lineWidth: 0,
minorTickInterval: null,
tickPixelInterval: 400,
tickWidth: 0,
title: {
y: -70
},
labels: {
y: 16
}
},
plotOptions: {
solidgauge: {
dataLabels: {
y: 5,
borderWidth: 0,
useHTML: true
},
}
}
};
// The speed gauge
$('#container').highcharts(Highcharts.merge(gaugeOptions, {
yAxis: {
min: 0,
max: 100,
title: {
text: ''
}
},
credits: {
enabled: false
},
series: [{
name: 'Speed',
data: [18.41],
includeInCSVExport:false,
dataLabels: {
format: '<div style="text-align:center"><span style="font-size:25px;color:' +
((Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black') + '">{}</span><br/>' +
'<span style="font-size:12px;color:silver"></span></div>'
},
tooltip: {
valueSuffix: ' %'
}
},{
name: 'Foo',
type: 'gauge',
data: [18.41]
}]
}));
// Bring life to the dials
setInterval(function () {
// Speed
var chart = $('#container-speed').highcharts(),
point,
newVal,
inc;
if(chart){
point = chart.series[0].points[0];
inc = Math.round((Math.random() - 0.5) * 100);
newVal = point.y + inc;
if(newVal < 0 || newVal > 100){
newVal = point.y - inc;
}
point.update(newVal);
point = chart.series[1].points[0];
point.update(newVal);
}
}, 2000);
Hi
There is issue with my csv export for gauge chart.
when I export a chart as a csv it downloades the chart as first column with value 0.
Is there any way to avoid that and get only one column for gauge type charts.
currently my csv contains data like below after downloading :
e.g. Micromarket | total stock (%)
0 | 18.41
But i want data should be like this after download :
e.g. total stock (%)
18.41
Please refer my below JS fiddle link for reference.
https://jsfiddle.net/pc9ggjm4/1/

How to use native date picker in both form and row editing in free jqgrid

Browser native datepicker is used for inline row editing as described in How to use input type='date' for date column in jqGrid
How to use it for form editing also?
I tried code below:
Selected row in grid
Pressed edit button in toolbar
Pressed save button in edit form
After that date disappears from grid invdate column.
Also pressing next and previous record buttons in edit form cause invdate to disappear.
How to edit and show date in edit form using browser native html5 date type picker if it is supported in browser ?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>https://stackoverflow.com/q/26040738/315935</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="author" content="Oleg Kiriljuk"/>
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.11.4/themes/redmond/jquery-ui.css"/>
<link rel="stylesheet" type="text/css" href="http://cdn.jsdelivr.net/free-jqgrid/4.8.0/css/ui.jqgrid.css"/>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<style type="text/css">
html, body { font-size: 75%; }
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/free-jqgrid/4.8.0/js/i18n/grid.locale-en.js"></script>
<script type="text/javascript">
$.jgrid = $.jgrid || {};
$.jgrid.no_legacy_api = true;
$.jgrid.useJSON = true;
</script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/free-jqgrid/4.8.0/js/jquery.jqgrid.src.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js"></script>
<script type="text/javascript">
//<![CDATA[
/*global $,Modernizr */
/*jslint browser: true, unparam: true */
$(function () {
"use strict";
var mydata = [
{ id: "10", invdate: "", name: "test1", note: "note1", amount: "200.00", tax: "10.00", closed: true, ship_via: "TN", total: "210.00" },
{ id: "20", invdate: "2007-10-02", name: "test2", note: "note2", amount: "300.00", tax: "20.00", closed: false, ship_via: "FE", total: "320.00" },
{ id: "30", invdate: "2007-09-01", name: "test3", note: "note3", amount: "400.00", tax: "30.00", closed: false, ship_via: "FE", total: "430.00" },
{ id: "40", invdate: "2007-10-04", name: "test4", note: "note4", amount: "200.00", tax: "10.00", closed: true, ship_via: "TN", total: "210.00" },
{ id: "50", invdate: "2007-10-31", name: "test5", note: "note5", amount: "300.00", tax: "20.00", closed: false, ship_via: "FE", total: "320.00" }
],
$grid = $("#list"),
initDateEdit = function (elem, options) {
// we need get the value before changing the type
var orgValue = $(elem).val(), newformat,
cm = $(this).jqGrid("getColProp", options.name);
$(elem).attr("type", "date");
if ((Modernizr && !Modernizr.inputtypes.date) || $(elem).prop("type") !== "date") {
// if type="date" is not supported call jQuery UI datepicker
$(elem).css({ width: "8em" }).datepicker({
dateFormat: "mm/dd/yy",
autoSize: true,
changeYear: true,
changeMonth: true,
showButtonPanel: true,
showWeek: true
});
} else {
// convert date to ISO
if (orgValue !== "") {
newformat = cm.formatoptions != null && cm.formatoptions.newformat ?
cm.formatoptions.newformat :
$(this).jqGrid("getGridRes", "formatter.date.newformat");
$(elem).val($.jgrid.parseDate.call(this, newformat, orgValue, "Y-m-d"));
}
// "10em" is better for Chrome and "11em" for Opera 24
$(elem).css("width", /OPR/.test(navigator.userAgent) ? "11em" : "10em");
}
},
myBeforeSaveRow = function (options, rowid) {
var $self = $(this), $dates = $("#" + $.jgrid.jqID(rowid)).find("input[type=date]");
$dates.each(function () {
var $this = $(this), newformat, str,
id = $this.attr("id"),
colName = id.substr(rowid.length + 1),
cm = $self.jqGrid("getColProp", colName);
if ((Modernizr && Modernizr.inputtypes.date) || $this.prop("type") === "date") {
// convert from iso to newformat
str = $this.val();
if (str !== "") {
newformat = cm.formatoptions != null && cm.formatoptions.newformat ?
cm.formatoptions.newformat :
$self.jqGrid("getGridRes", "formatter.date.newformat");
str = $.jgrid.parseDate.call($self[0], "Y-m-d", str, newformat);
}
$this.attr("type", "text");
$this.val(str);
}
});
},
initDateSearch = function (elem) {
setTimeout(function () {
$(elem).datepicker({
dateFormat: "mm/dd/yy",
autoSize: true,
changeYear: true,
changeMonth: true,
showWeek: true,
showButtonPanel: true
});
}, 50);
},
numberTemplate = {formatter: "number", align: "right", sorttype: "number",
editrules: {number: true, required: true},
searchoptions: { sopt: ["eq", "ne", "lt", "le", "gt", "ge", "nu", "nn", "in", "ni"] }};
$grid.jqGrid({
datatype: "local",
//loadComplete: function() {
// $grid.jqGrid('setGridParam', { datatype: 'json' });
//},
data: mydata,
colNames: ["Client", "Date", "Closed", "Shipped via", "Notes", "Tax", "Amount", "Total"],
colModel: [
{ name: "name", align: "center", editable: true, width: 65, editrules: {required: true} },
{ name: "invdate", width: 125, align: "center", sorttype: "date",
formatter: "date", /*formatoptions: { newformat: "m/d/Y"},*/ editable: true,
editoptions: { dataInit: initDateEdit },
searchoptions: { sopt: ["eq", "ne", "lt", "le", "gt", "ge"], dataInit: initDateSearch } },
{ name: "closed", width: 70, align: "center", editable: true, formatter: "checkbox",
edittype: "checkbox", editoptions: {value: "Yes:No", defaultValue: "Yes"},
stype: "select", searchoptions: { sopt: ["eq", "ne"], value: ":Any;true:Yes;false:No" } },
{ name: "ship_via", width: 105, align: "center", editable: true, formatter: "select",
edittype: "select", editoptions: { value: "FE:FedEx;TN:TNT;IN:Intim", defaultValue: "IN" },
stype: "select", searchoptions: { sopt: ["eq", "ne"], value: ":Any;FE:FedEx;TN:TNT;IN:IN" } },
{ name: "note", width: 60, sortable: false, editable: true, edittype: "textarea" },
{ name: "tax", width: 52, editable: true, template: numberTemplate },
{ name: "amount", width: 75, editable: true, template: numberTemplate },
{ name: "total", width: 60, template: numberTemplate }
],
rowNum: 10,
rowList: [5, 10, 20],
iconSet: "fontAwesome",
pager: "#pager",
gridview: true,
autoencode: true,
ignoreCase: true,
sortname: "invdate",
viewrecords: true,
sortorder: "desc",
height: "auto",
rownumbers: true,
editurl: "clientArray",
//editurl: "http://cdn.jsdelivr.net/test",
toppager: true,
onSelectRow: function (rowid) {
var $self = $(this),
savedRow = $self.jqGrid("getGridParam", "savedRow");
if (savedRow.length > 0) {
$self.jqGrid("restoreRow", savedRow[0].id);
}
$self.jqGrid("editRow", rowid, {
keys: true,
beforeSaveRow: myBeforeSaveRow
});
}
});
$.extend(true,$.jgrid.edit, {
closeAfterAdd: true,
navkeys: [true,33,34],
savekey: [true, 13],
recreateForm: true,
reloadAfterSubmit: false,
left: 10,
top: 15,
dataheight: '100%',
width: window.innerWidth - 18
});
$grid.jqGrid("navGrid", "#list_toppager", {
edit: true
});
});
//]]>
</script>
</head>
<body>
<table id="list"><tr><td></td></tr></table>
<div id="pager"></div>
</body>
</html>
The workaround used in myBeforeSaveRow need be implemented in form editing too. Instead of that I changed the code of free jqGrid so that you **don't need to use beforeSaveRow: myBeforeSaveRow at all. I adjusted the code of inline editing and form editing so that it works correctly on saving the data from <input type="date">. One should be only careful and set the value of type to text if type="date" is not supported.
The demo uses the current code of free jqGrid from GitHub. I tested the demo in Chrome 41, Opera 28 where <input type="date"> is supported. I tested the changes in Safari 5.1.7, Firefox 37 and IE 10. The demo works here too. It use the following modified code of initDateEdit:
var initDateEdit = function (elem, options) {
// we need get the value before changing the type
var orgValue = $(elem).val(), newformat,
cm = $(this).jqGrid("getColProp", options.name);
$(elem).attr("type", "date");
if ((typeof Modernizr !== "undefined" && !Modernizr.inputtypes.date) || $(elem).prop("type") !== "date") {
$(elem).attr("type", "text"); // !!! important to make saving works correctly
$(elem).css({ width: "8em" }).datepicker({
dateFormat: "mm/dd/yy",
autoSize: true,
changeYear: true,
changeMonth: true,
showButtonPanel: true,
showWeek: true
});
} else {
// convert date to ISO
if (orgValue !== "") {
newformat = cm.formatoptions != null && cm.formatoptions.newformat ?
cm.formatoptions.newformat :
$(this).jqGrid("getGridRes", "formatter.date.newformat");
$(elem).val($.jgrid.parseDate.call(this, newformat, orgValue, "Y-m-d"));
}
$(elem).css({width: "11em"});
}
};
The other code of inline and form editing is the standard:
...
onSelectRow: function (rowid) {
var $self = $(this),
savedRow = $self.jqGrid("getGridParam", "savedRow");
if (savedRow.length > 0 && savedRow[0].id !== rowid) {
$self.jqGrid("restoreRow", savedRow[0].id);
}
$self.jqGrid("editRow", rowid);
},
inlineEditing: {
keys: true
}
}).jqGrid("navGrid").jqGrid("inlineNav");
The options beforeSaveRow: myBeforeSaveRow are removed.

Highcharts bargraph from json data in angularJS

I have a highcharts bargraph whose values are received from json whose format is as follows:
"bargraph":
[
{
"categories": "['S', 'M', 'T', 'W', 'T', 'F']",
"series1": "[800, 1100, 80, 1800, 1600, 2000]",
"series2": "[800, 1100, 80, 1800, 1200, 800]"
}
]
How can i embed those values for my bargraph in angularJS
HTML Code:
<div id="bargraph" bargraph={{bargraph}}><\div>
Directive:
angular.module('example').directive('bargraph', function () {
element.highcharts({
xAxis: [
{
categories: [] //embed categories value here
},
series: [
{
name: 'series1',
data: [] //Embed series1 data here
},
{
name: 'series2',
data: [] //Embed series2 data here
}
]
})
})
Please provide a suitable way to embed the data from json.
Here is a directive i copied and pasted from my webapp it is how i render highcharts using a directive NOTE: not all of this directive is applicable to you and some of it is specific to what i needed but you get the idea.
lrApp.directive('chart', function () {
return {
restrict: 'E',
template: '<div></div>',
transclude: true,
replace: true,
link: function (scope, element, attrs) {
var chart = null;
var chartsDefaults = {
chart: {
renderTo: element[0],
type: attrs.type || null,
height: attrs.height || null,
width: attrs.width || null,
},
colors: scope.$eval(attrs.colors) || null,
title: {
style: {
display: 'none'
}
},
xAxis: {
//categories: ['{"-7 days"|date_format}','{"-6 days"|date_format}','{"-5 days"|date_format}','{"-4 days"|date_format}', '{"-3 days"|date_format}', '{"-2 days"|date_format}', '{"-1 day"|date_format}', '{$smarty.now|date_format}'],
categories: scope.$eval(attrs.dates) || null,
gridLineDashStyle: 'ShortDot',
gridLineColor: "#C0C0C0",
gridLineWidth: 1,
labels: {
y: 27
}
},
yAxis: {
title: {
text: null
},
min: 0,
gridLineDashStyle: 'ShortDot',
gridLineColor: "#C0C0C0",
gridLineWidth: 1
},
credits: {
enabled: false
},
legend: {
enabled: false
},
plotOptions: {
series: {
shadow: false,
lineWidth: 3
}
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
this.x + ': ' + this.y + '</b>';
}
}
};
//Update when charts data changes
scope.$watch(attrs.value, function (newVal, oldVal) {
if (!newVal.length) return;
// We need deep copy in order to NOT override original chart object.
// This allows us to override chart data member and still the keep
// our original renderTo will be the same
var deepCopy = true;
var newSettings = {};
chartsDefaults.series = newVal;
chartsDefaults.colors = scope.$eval(attrs.colors);
chartsDefaults.xAxis.categories = scope.$eval(attrs.dates);
console.log(chartsDefaults);
chart = new Highcharts.Chart(chartsDefaults);
});
}
}
});
and this is how it used it obviously you would change "line" to bar:
<chart value="stats.sets" dates="stats.days" colors="stats.colors" type="line"></chart>