Zoom Google chart - querySelector - google-apps-script

I would like so much to learn how to solve this puzzle: The function zoom is not working, I tried everything... I don't know what to do... I can't figure out what is missing in the code.
I would like to share one example that's working:
[http://jsfiddle.net/0wb2zvye/3/][1]
<!DOCTYPE html>
<html lang="en-US">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>
Google Visualization API Sample
</title>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="https://apis.google.com/js/platform.js"> {lang: 'en-US'}</script>
<script type="text/javascript">
google.load('visualization', '1.1', {packages: ['corechart', 'controls'],'language': 'en-US'});
</script>
</head>
<style>
</style>
<body style="font-family: Arial;border: 0 none;">
<div id="dashboard" style="width:1350px;overflow:scroll;">
Zoom<br />
<input id="lastA" type="button" value="Mon" />
<input id="lastB" type="button" value="Tue" />
<input id="lastC" type="button" value="Wed" />
<input id="lastD" type="button" value="Thu" />
<input id="lastE" type="button" value="Fri" />
<input id="lastF" type="button" value="Sat" />
<input id="lastG" type="button" value="Sun" />
<div id="chart" style="position: relative; width: 1350px; height: 500px;"></div>
<div id="control" style='width: 1350px; height: 50px;'></div>
<div id="filter_div"></div>
</div>
<div id="junk_div" style="display: none;"></div>
<script type="text/javascript">
var data;
var dataTable;
var dashboard;
google.load("visualization", "1", {packages:["controls", "corechart"]});
google.setOnLoadCallback(drawVisualization);
function setupData(){
var control = new google.visualization.ControlWrapper({
'controlType': 'ChartRangeFilter',
'containerId': 'control',
'options': {
// Filter by the date axis.
'filterColumnIndex': 0,
'ui': {
'chartType': 'LineChart',
'chartOptions': {
'chartArea': {'width': '90%'},
'hAxis': {'baselineColor': 'none'}
},
'chartView': {
'columns': [0, 1, 2]
},
'minRangeSize': 1
}
},
// Initial range: 1 to 4.
'state': {'range': {'start': 1, 'end': 50}},
view: {
columns: [{
type: 'number',
calc: function (dt, row) {
return {v: row, f: dt.getFormattedValue(row, 0)};
}
}, 1, 2]
}
});
//then reverse the process in the ChartWrapper's view.columns:
var dateFormatter = new google.visualization.DateFormat({pattern: 'E \nHH:mm', 'textStyle':{'fontSize': 8}});
dateFormatter.format(data, 0);
var chart = new google.visualization.ChartWrapper({
'chartType': 'AreaChart',
'containerId': 'chart',
'options': {
'title':'Wharehouse overwiew',
// Use the same chart area width as the control for axis alignment.
'chartArea': {'height': '80%', 'width': '90%'},
'vAxis': {'viewWindowMode':'explicit','viewWindow': {'min': 0},'gridlines': { 'count': 10, 'color': '#d9e2d9' } ,'textStyle':{'fontSize': 11}},
'legend': { 'position': 'top', 'alignment': 'start' },
'hAxis': {'format': 'E /nHH:mm','textStyle':{'fontSize': 8},'minTextSpacing': 0, 'slantedText': false},
'tooltip': { 'textStyle': { 'fontName': 'verdana', 'fontSize': 10, 'color': '#2d862d' } },
'series': {
0: { 'areaOpacity': 0.1},
1: { 'areaOpacity': 0.1}
}
// 'trendlines': {0: {'color': 'black','lineWidth': 3,'opacity': 0.4 }}
// hAxis: { 'minTextSpacing': 0, 'showTextEvery': 1, slantedText: true }
},
view: {
columns: [{
type: 'string',
label: data.getColumnLabel(0),
calc: function (dt, row) {
return dt.getFormattedValue(row, 0);
}
}, 1, 2]
}
});
console.log('label: ' + data.getColumnLabel(0));
var dashboard = new google.visualization.Dashboard(document.querySelector('#dashboard'));
dashboard.bind(control, chart).bind(filter, control);
dashboard.draw(data);
function zoomLastA () {
var range = data.getColumnRange(0);
control.setState({
range: {
start: new Date(range.max.getFullYear(), range.max.getMonth(), range.max.getDate() - 1),
end: range.max
}
});
control.draw();
}
function zoomLastB () {
var range = data.getColumnRange(0);
control.setState({
range: {
start: new Date(range.max.getFullYear(), range.max.getMonth(), range.max.getDate() - 2),
end: range.max
}
});
control.draw();
}
function zoomLastC () {
var range = data.getColumnRange(0);
control.setState({
range: {
start: new Date(range.max.getFullYear(), range.max.getMonth(), range.max.getDate() -3),
end: range.max
}
});
control.draw();
}
function zoomLastD () {
var range = data.getColumnRange(0);
control.setState({
range: {
start: new Date(range.max.getFullYear(), range.max.getMonth(), range.max.getDate() -4),
end: range.max
}
});
control.draw();
}
function zoomLastE () {
var range = data.getColumnRange(0);
control.setState({
range: {
start: new Date(range.max.getFullYear(), range.max.getMonth(), range.max.getDate() -5),
end: range.max
}
});
control.draw();
}
function zoomLastF () {
var range = data.getColumnRange(0);
control.setState({
range: {
start: new Date(range.max.getFullYear(), range.max.getMonth(), range.max.getDate() -6),
end: range.max
}
});
control.draw();
}
function zoomLastG () {
var range = data.getColumnRange(0);
control.setState({
range: {
start: new Date(range.max.getFullYear(), range.max.getMonth(), range.max.getDate() -7),
end: range.max
}
});
control.draw();
}
var runOnce = google.visualization.events.addListener(dashboard, 'ready', function () {
google.visualization.events.removeListener(runOnce);
if (document.addEventListener) {
document.querySelector('#lastA').addEventListener('click', zoomLastA);
document.querySelector('#lastB').addEventListener('click', zoomLastB);
document.querySelector('#lastC').addEventListener('click', zoomLastC);
document.querySelector('#lastD').addEventListener('click', zoomLastD);
document.querySelector('#lastE').addEventListener('click', zoomLastE);
document.querySelector('#lastF').addEventListener('click', zoomLastF);
document.querySelector('#lastG').addEventListener('click', zoomLastG);
}
else if (document.attachEvent) {
document.querySelector('#lastA').attachEvent('onclick', zoomLastA);
document.querySelector('#lastB').attachEvent('onclick', zoomLastB);
document.querySelector('#lastC').attachEvent('onclick', zoomLastC);
document.querySelector('#lastD').attachEvent('onclick', zoomLastD);
document.querySelector('#lastE').attachEvent('onclick', zoomLastE);
document.querySelector('#lastF').attachEvent('onclick', zoomLastF);
document.querySelector('#lastG').attachEvent('onclick', zoomLastG);
}
else {
document.querySelector('#lastA').onclick = zoomLastA;
document.querySelector('#lastB').onclick = zoomLastB;
document.querySelector('#lastC').onclick = zoomLastC;
document.querySelector('#lastD').onclick = zoomLastD;
document.querySelector('#lastE').onclick = zoomLastE;
document.querySelector('#lastF').onclick = zoomLastF;
document.querySelector('#lastG').onclick = zoomLastG;
}
});
}
function drawVisualization() {
dataTable = new google.visualization.DataTable();
dashboard = new google.visualization.Dashboard(document.getElementById('#dashboard'));

Related

How Kendo grid select row get the selected userID?

Hi i need some help for to get the select row id as i realize i am able to get my ajax from my response however is there a way where i select the row i can display the id selected one ?
Updated by using the new onchange i have make a selected id however i got error still
var dataSource = new kendo.data.DataSource({
read: {
url: "https://ecoexchange.dscloud.me:8090/api/get",
dataType: "JSON",
method: "GET",
headers: {
query: "UserGet(1)",
// Gets the apikey from the sessionStorage
apikey: sessionStorage.getItem("apikey")
}
},
});
$("#user-list").kendoGrid({
dataSource: dataSource,
height: $(window).height() - $("#user-list").position()["top"] - 130,
selectable: "single, row",
change: function(e) {
var selectedRows = this.select();
var selectedDataItems = [];
for (var i = 0; i < selectedRows.length; i++) {
var dataItem = this.dataItem(selectedRows[i]);
selectedDataItems.push(dataItem);
}
// selectedDataItems contains all selected data items
/* The result can be observed in the DevTools(F12) console of the browser. */
if (selectedDataItems && selectedDataItems.length > 0) {
$("#selection")[0].innerHTML = selectedDataItems[0].UserID;
}
},
// width: $(window).width()-$("#customer-list").position()["width"]-10,
//pageSize: 10,
scrollable: {
endless: true,
},
columns: [
{
field: "",
title: "Profile",
headerAttributes: {
"class": "k-text-center"
},
width: 150
},
{
field: "",
title: "User Name",
},
],
});
$("#user-list tbody").on("click", "tr", function(e) {
const btns = $('.select-row');
var rowElement = this;
var row = $(rowElement);
var grid = $("#user-list").getKendoGrid();
if (row.hasClass("k-state-selected")) {
var selected = grid.select();
selected = $.grep(selected, function(x) {
var itemToRemove = grid.dataItem(row);
var currentItem = grid.dataItem(x);
return itemToRemove != currentItem
})
btns.prop('disabled', true).removeClass('disabled dark');
grid.clearSelection();
grid.select(selected);
e.stopPropagation();
} else {
grid.select(row)
e.stopPropagation();
btns.prop('disabled', false).removeClass('disabled dark');
}
});
I am calling my ajax to kendo grid where kendo grid created the grid and the selected row
This is how the page look like
However i have no idea how to select the row display the userID display where then if this is selected when press view details the information be pass into there
This is the response example
[
{
"UserID": 1,
"Name": "Kelyn Wong",
"Username": "kelynwong",
"Email": "kelynwonget#gmail.com",
"Picture": null,
"UserRole": "Approving Admin"
},
{
"UserID": 2,
"Name": "Kai Jie",
"Username": "kaijie",
"Email": "test#gmail.com",
"Picture": null,
"UserRole": "Admin"
},
This is how the row selected look like when the user select the row
This the whole code from body to script from using ajax to kendo grid
< script >
/* Call the ajax to load to load to #customer-list tbody */
$.ajax({
url: "https://ecoexchange.dscloud.me:8090/api/get",
method: "GET",
// In this case, we are going to use headers as
headers: {
// The query you're planning to call
// i.e. <query> can be UserGet(0), RecyclableGet(0), etc.
query: "UserGet(0)",
// Gets the apikey from the sessionStorage
apikey: sessionStorage.getItem("apikey")
},
success: function(data, xhr, textStatus) {
//console.log(data)
const buildTable = data => {
const table = document.querySelector("#user-list tbody");
for (let i = 0; i < data.length; i++) {
let row =
`
<tr>
<td class="cell-user-name"style="padding-left: 20px;"><img src = "${data[i].Picture}" class="picture" width="100px" height="100px" onError="this.onerror=null;this.src='../../assets/images/placeholder-avatar.jpg';" ></img></td>
<td class="cell-user-name" style="padding-right: 80px; padding-top: 10px; font-weight: bold; font-size: 18px;">${data[i].Name}</td>
</tr>
`;
table.insertAdjacentHTML('beforeEnd', row);
}
};
// Fetch method
const getData = async(url) => {
const response = await fetch(url, {
method: 'GET',
headers: {
query: "UserGet(0)",
// Gets the apikey from the sessionStorage
apikey: sessionStorage.getItem("apikey")
}
});
const json = await response.json();
$("#loading-container").hide();
return buildTable(json);
};
/*Error GET http://127.0.0.1:5501/testEnv/view/public/manageCustomers/null 404 (Not Found) */
/* But code are able to fetch the data */
getData("https://ecoexchange.dscloud.me:8090/api/get")
},
error: function(xhr, textStatus, err) {
console.log(err);
}
});
$(window).on("resize", function(e) {
console.log("width:", $("#user-list").width(), "height:", $("#user-list").height())
});
$("#user-list").kendoGrid({
height: $(window).height() - $("#user-list").position()["top"] - 130,
selectable: "single",
// width: $(window).width()-$("#customer-list").position()["width"]-10,
//pageSize: 10,
scrollable: {
endless: true,
},
columns: [
{
field: "",
title: "Profile",
headerAttributes: {
"class": "k-text-center"
},
width: 150
},
{
field: "",
title: "User Name",
},
],
});
$("#user-list tbody").on("click", "tr", function(e) {
const btns = $('.select-row');
var rowElement = this;
var row = $(rowElement);
var grid = $("#user-list").getKendoGrid();
if (row.hasClass("k-state-selected")) {
var selected = grid.select();
selected = $.grep(selected, function(x) {
var itemToRemove = grid.dataItem(row);
var currentItem = grid.dataItem(x);
return itemToRemove != currentItem
})
btns.prop('disabled', true).removeClass('disabled dark');
grid.clearSelection();
grid.select(selected);
e.stopPropagation();
} else {
grid.select(row)
e.stopPropagation();
btns.prop('disabled', false).removeClass('disabled dark');
}
});
// <!-- Search bar function -->
$("#search-user-name").on("keyup change", function() {
var usernames = $("#search-user-name").val().toLowerCase();
//console.log(usernames);
if (usernames == "") {
$('#user-list tbody tr td.cell-user-name').parent().show();
} else {
$("#user-list tbody tr").filter(function() {
var usernameText = $(this).children("td.cell-user-name").text().toLowerCase();
$(this).toggle(
(usernameText.indexOf(usernames) >= 0)
);
})
};
})
<
/script>
<!-- the white rectange body contain-->
<div id="container-body">
<div class="col-12">
<br />
<div class="input-group">
<!-- Length of the search bar -->
<div class="col-md-10">
<!-- Search bar components -->
<span id="search-icon" class="fa fa-search search-icon-span"></span>
<input class="search-input form-control" placeholder="Name" type="text" name="User Name" id="search-user-name">
</div>
<!-- button all of it-->
<fieldset class='btn-group'>
<button onclick="window.location.href='addUsers.html'" id="add" type="button" class="btn btn-primary btn custom mr-1 mb-2" style="border-radius: 5px;">Add </button>
<button onclick="window.location.href=''" id="edit" type="button" class=" btn-primary btn custom mr-1 mb-2 disabled select-row" style="border-radius: 5px; margin-left: 5px;" disabled>View Details</button>
</fieldset>
<div class="col-md-12">
<div class="table-responsive" style="overflow:hidden; padding-top: 20px;">
<table id="user-list" class="table">
<!-- Loading Spinner Div -->
<div id="loading-container">
<p>Fetching all users data...</p>
<div id="loading-spinner">
</div>
<tbody>
</tbody>
</table>
</div>
</div>
You can use the change event of the Kendo Grid to get the selected row. See the snippet below for a demo from the Kendo documentation.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Kendo UI Snippet</title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2021.3.1207/styles/kendo.default-v2.min.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2021.3.1207/js/kendo.all.min.js"></script>
</head>
<body>
<label>
Selection: <span id="selection"></span>
</label>
<div id="grid"></div>
<script>
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "https://demos.telerik.com/kendo-ui/service/products",
dataType: "jsonp"
}
},
pageSize: 10
});
$("#grid").kendoGrid({
dataSource: dataSource,
selectable: "single, row",
change: function(e) {
console.log("change", this.dataItem(this.select()[0]));
const selection = this.select();
if (selection && selection.length > 0) {
$("#selection")[0].innerHTML = this.dataItem(selection[0]).ProductID;
}
}
});
</script>
</body>
</html>

Inject html into ng2-chart tooltip to preview image

I have images with scores associated with them streaming to my app. As the scores come in I've plotted them on a line chart using ng2-charts.
I want to customize the tooltip on the chart to display a smaller preview of the image that it came with. I've scoured around but haven't been able to figure out how to inject the custom html into the tooltip or if it is even possible without creating a custom chart.
Any advice on whether or not this is possible and how would be greatly appreciated.
This is in Ionic 4 with angular 6 and my modules versions are:
"ng2-charts": "^2.2.2",
"chart.js": "^2.8.0",
Not sure this is necessary for my question but here's how I set up the chart so far.
Markdown
<ion-content padding>
<div class="row" style="display: block;">
<div class="col-md-6">
<div style="display: block;">
<canvas baseChart width="1200" height="600"
[datasets]="lineChartData"
[labels]="lineChartLabels"
[options]="lineChartOptions"
[colors]="lineChartColors"
[legend]="lineChartLegend"
[chartType]="lineChartType"
(chartHover)="chartHovered($event)"
(chartClick)="chartClicked($event)"></canvas>
</div>
</div>
</div>
</ion-content>
Initializing the chart
// Initializing Chart settings
public lineChartLegend:boolean = true;
public lineChartType:string = 'line';
public lineChartData:ChartDataSets[] = [{ data: this.scoreArr, label: 'Image Scores' }];
public lineChartLabels:Label[] = [];
public lineChartOptions: (ChartOptions & { annotation: any }) = {
responsive: true,
scales: {
// We use this empty structure as a placeholder for dynamic theming.
xAxes: [{}],
yAxes: [
{
id: 'y-axis-0',
position: 'left',
}
]
},
annotation: {
annotations: [
{
type: 'line',
mode: 'vertical',
scaleID: 'x-axis-0',
value: 'March',
borderColor: 'orange',
borderWidth: 2,
label: {
enabled: true,
fontColor: 'orange',
content: 'LineAnno'
}
},
],
}
};
public lineChartColors:Color[] = [
{ // dark grey
backgroundColor: 'rgba(77,83,96,0.2)',
borderColor: 'rgba(77,83,96,1)',
pointBackgroundColor: 'rgba(77,83,96,1)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(77,83,96,1)'
}
];
To anyone who is curious. This is how. However, the tooltip doesn't go away when you stop hovering but I'll figure it out in a bit.
customTooltips = function(tooltip) {
//**************** This is what was messing me up
var tooltipEl = document.getElementById('chartjs-tooltipsdfljsdflkswdjf');
// Apparently grabbing my existing tooltipel was causing my issue
// if you make tooltipel null and just make your own following the
// chart.js docs this will work fine.
// ***************
if (!tooltipEl) {
console.log("tooltipel was null");
tooltipEl = document.createElement('div');
tooltipEl.id = 'chartjs-tooltip';
tooltipEl.innerHTML = "<table></table>"
document.body.appendChild(tooltipEl);
}
// Hide if no tooltip
if (tooltip.opacity === 0) {
tooltipEl.style.opacity = '0';
return;
}
tooltipEl.classList.remove('above','below','no-transform');
if (tooltip.yAlign) {
tooltipEl.classList.add(tooltip.yAlign);
} else {
tooltipEl.classList.add('no-transform');
}
function getBody(bodyItem) {
return bodyItem.lines;
}
// Set Text
if (tooltip.body) {
console.log("Bodys not null: ", tooltip.body);
var titleLines = tooltip.title || [];
var bodyLines = tooltip.body.map(getBody);
var innerHtml = '<thead>';
titleLines.forEach(function(title) {
innerHtml += '<tr><th>' + title + '</th></tr>';
innerHtml += '<tr><th><img src="https://www.mariowiki.com/images/thumb/2/2b/Marioptds.png/146px-Marioptds.png" style="width:42px;height:42px;border:0;"/></th></tr>';
});
innerHtml += '</thead><tbody>';
bodyLines.forEach(function(body, i) {
var colors = tooltip.labelColors[i];
var style = 'background:' + colors.backgroundColor;
style += '; border-color:' + colors.borderColor;
style += '; border-width: 2px';
var span = '<span class="chartjs-tooltip-key" style="' + style + '"></span>';
innerHtml += '<tr><td>' + span + body + '</td></tr>';
});
innerHtml += '</tbody>';
var tableRoot = tooltipEl.querySelector('table');
console.log('TableRoot: ' + tableRoot);
tableRoot.innerHTML = innerHtml;
}
// `this` will be the overall tooltip
var position = this._chart.canvas.getBoundingClientRect();
// Display, position, and set styles for font
tooltipEl.style.opacity = '1';
tooltipEl.style.position = 'absolute';
tooltipEl.style.left = position.left + window.pageXOffset + tooltip.caretX + 'px';
tooltipEl.style.top = position.top + window.pageYOffset + tooltip.caretY + 'px';
tooltipEl.style.fontFamily = tooltip._bodyFontFamily;
tooltipEl.style.fontSize = tooltip.bodyFontSize + 'px';
tooltipEl.style.fontStyle = tooltip._bodyFontStyle;
tooltipEl.style.padding = tooltip.yPadding + 'px ' + tooltip.xPadding + 'px';
tooltipEl.style.pointerEvents = 'none';
};
// Initializing Chart settings
public lineChartLegend:boolean = true;
public lineChartType:string = 'line';
public lineChartData:ChartDataSets[] = [{ data: this.scoreArr, label: 'Image Scores' }];
public lineChartLabels:Label[] = [];
public lineChartOptions: (ChartOptions & { annotation: any }) = {
responsive: true,
scales: {
// We use this empty structure as a placeholder for dynamic theming.
xAxes: [{}],
yAxes: [
{
id: 'y-axis-0',
position: 'left',
}
]
},
annotation: {
annotations: [
{
type: 'line',
mode: 'vertical',
scaleID: 'x-axis-0',
value: 'March',
borderColor: 'orange',
borderWidth: 2,
label: {
enabled: true,
fontColor: 'orange',
content: 'LineAnno'
}
},
],
},
tooltips: {
enabled: false,
mode: 'index',
position: 'nearest',
custom: this.customTooltips
}
};
public lineChartColors:Color[] = [
{ // dark grey
backgroundColor: 'rgba(77,83,96,0.2)',
borderColor: 'rgba(77,83,96,1)',
pointBackgroundColor: 'rgba(77,83,96,1)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(77,83,96,1)'
}
];

Angular JS add an URL or ng-click event on Calender date

First of all, I very new in Angular JS framework, I am implementing Angular Calender. For on click on date i want to call method. How can i give href or ng-click method call ?
Please suggest how to give method call through script !!
<!DOCTYPE html>
<html lang="en" ng-app="calendarDemoApp" id="top">
<head>
<title>AngularUI Calendar for AngularJS</title>
<link rel="icon" href="favicon.ico" />
<link rel="stylesheet" href="/../bower_components/bootstrap-css/css/bootstrap.css" />
<link rel="stylesheet" href="/../bower_components/fullcalendar/dist/fullcalendar.css">
<link rel="stylesheet" href="calendarDemo.css" />
<script src="../bower_components/jquery/dist/jquery.js"></script>
<script src="../bower_components/angular/angular.js"></script>
<script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.13.0.js"></script>
<script src="../bower_components/moment/moment.js"></script>
<script src="../bower_components/fullcalendar/dist/fullcalendar.js"></script>
<script src="../bower_components/fullcalendar/dist/gcal.js"></script>
<script src="../src/calendar.js"></script>
<script src="calendarDemo.js"></script>
</head>
<body data-spy="scroll">
<header class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<div class="dropdown pull-left">
<a class="brand dropdown-toggle" role="button" data-toggle="dropdown" href="#">
AngularUI
<b class="caret"></b>
</a>
<ul class="dropdown-menu" role="menu" aria-labelledby="dLabel">
<li><strong>Related Projects:</strong></li>
<li class="divider"></li>
<li>Bootstrap</li>
<li>Grid</li>
<li>AngularJS.tmbundle</li>
<li><a href="http://angular-ui.github.io/ui-router/sample/">Router <span
class="label label-success">New!</span></a></li>
<li><a href="http://angular-ui.github.com/Tips-n-Tricks/">Tips-n-Tricks <span
class="label">WIP</span></a></li>
</ul>
</div>
</div>
</div>
</header>
<div class="hero-unit">
<div class="container">
<h1>UI Calendar</h1>
<p>A complete AngularJS directive for the Arshaw FullCalendar.</p>
<p class="btn-group">
<a href="https://github.com/angular-ui/ui-calendar" class='btn'><i class='icon-github'></i> Code on Github</a>
</i> Download <small>(0.8.1)</small>
</p>
</div>
<div class="bs-docs-social">
<div class="container">
<ul class="bs-docs-social-buttons">
<li>
<iframe src="http://ghbtns.com/github-btn.html?user=angular-ui&repo=ui-calendar&type=watch&count=true" allowtransparency="true" frameborder="0" scrolling="0" width="110" height="20"></iframe>
</li>
<li>
<iframe src="http://ghbtns.com/github-btn.html?user=angular-ui&repo=ui-calendar&type=fork&count=true" allowtransparency="true" frameborder="0" scrolling="0" width="95" height="20"></iframe>
</li>
<li>
<div class="g-plusone" data-size="medium"></div>
<!-- Place this tag after the last +1 button tag. -->
<script type="text/javascript">
(function() {
var po = document.createElement('script');
po.type = 'text/javascript';
po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(po, s);
})();
</script>
</li>
</ul>
</div>
</div>
</div>
<div role="main">
<div class="container">
<section id="directives-calendar" ng-controller="CalendarCtrl">
<div class="page-header">
<h1>UI-Calendar</h1>
</div>
<h3>Calender</h3>
<pre class="prettyprint linenums">
<div ui-calendar="{{uiConfig.calendar}}" class="span8 calendar" ng-model="eventSources"></div>
</pre>
</section>
</div>
</div>
Javascript Code:
/**
* calendarDemoApp - 0.9.0
*/
angular.module('calendarDemoApp', ['ui.calendar', 'ui.bootstrap']);
function CalendarCtrl($scope, $compile, uiCalendarConfig) {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$scope.changeTo = 'Hungarian';
/* event source that pulls from google.com */
$scope.eventSource = {
url: "http://www.google.com/calendar/feeds/usa__en%40holiday.calendar.google.com/public/basic",
className: 'gcal-event', // an option!
currentTimezone: 'America/Chicago' // an option!
};
/* event source that contains custom events on the scope */
$scope.events = [{
title: 'All Day Event',
start: new Date(y, m, 1)
}, {
title: 'Long Event',
start: new Date(y, m, d - 5),
end: new Date(y, m, d - 2)
}, {
id: 999,
title: 'Repeating Event',
start: new Date(y, m, d - 3, 16, 0),
allDay: false
}, {
id: 999,
title: 'Repeating Event',
start: new Date(y, m, d + 4, 16, 0),
allDay: false
}, {
title: 'Birthday Party',
start: new Date(y, m, d + 1, 19, 0),
end: new Date(y, m, d + 1, 22, 30),
allDay: false
}, {
title: 'Click for Google',
start: new Date(y, m, 28),
end: new Date(y, m, 29),
url: 'http://google.com/'
}];
/* For Title i want to assign href or ng-click */
/* event source that calls a function on every view switch */
$scope.eventsF = function(start, end, timezone, callback) {
var s = new Date(start).getTime() / 1000;
var e = new Date(end).getTime() / 1000;
var m = new Date(start).getMonth();
var events = [{
title: 'Feed Me ' + m,
start: s + (50000),
end: s + (100000),
allDay: false,
className: ['customFeed']
}];
callback(events);
};
$scope.calEventsExt = {
color: '#f00',
textColor: 'yellow',
events: [{
type: 'party',
title: 'Lunch',
start: new Date(y, m, d, 12, 0),
end: new Date(y, m, d, 14, 0),
allDay: false
}, {
type: 'party',
title: 'Lunch 2',
start: new Date(y, m, d, 12, 0),
end: new Date(y, m, d, 14, 0),
allDay: false
}, {
type: 'party',
title: 'Click for Google',
start: new Date(y, m, 28),
end: new Date(y, m, 29),
url: 'http://google.com/'
}]
};
/* alert on eventClick */
$scope.alertOnEventClick = function(date, jsEvent, view) {
$scope.alertMessage = (date.title + ' was clicked ');
};
/* alert on Drop */
$scope.alertOnDrop = function(event, delta, revertFunc, jsEvent, ui, view) {
$scope.alertMessage = ('Event Dropped to make dayDelta ' + delta);
};
/* alert on Resize */
$scope.alertOnResize = function(event, delta, revertFunc, jsEvent, ui, view) {
$scope.alertMessage = ('Event Resized to make dayDelta ' + delta);
};
/* add and removes an event source of choice */
$scope.addRemoveEventSource = function(sources, source) {
var canAdd = 0;
angular.forEach(sources, function(value, key) {
if (sources[key] === source) {
sources.splice(key, 1);
canAdd = 1;
}
});
if (canAdd === 0) {
sources.push(source);
}
};
/* add custom event*/
$scope.addEvent = function() {
$scope.events.push({
title: 'Open Sesame',
start: new Date(y, m, 28),
end: new Date(y, m, 29),
className: ['openSesame']
});
};
/* remove event */
$scope.remove = function(index) {
$scope.events.splice(index, 1);
};
/* Change View */
$scope.changeView = function(view, calendar) {
uiCalendarConfig.calendars[calendar].fullCalendar('changeView', view);
};
/* Change View */
$scope.renderCalender = function(calendar) {
if (uiCalendarConfig.calendars[calendar]) {
uiCalendarConfig.calendars[calendar].fullCalendar('render');
}
};
/* Render Tooltip */
$scope.eventRender = function(event, element, view) {
element.attr({
'tooltip': event.title,
'tooltip-append-to-body': true
});
$compile(element)($scope);
};
/* config object */
$scope.uiConfig = {
calendar: {
height: 450,
editable: true,
header: {
left: 'title',
center: '',
right: 'today prev,next'
},
eventClick: $scope.alertOnEventClick,
eventDrop: $scope.alertOnDrop,
eventResize: $scope.alertOnResize,
eventRender: $scope.eventRender
}
};
$scope.changeLang = function() {
if ($scope.changeTo === 'Hungarian') {
$scope.uiConfig.calendar.dayNames = ["Vasárnap", "Hétfő", "Kedd", "Szerda", "Csütörtök", "Péntek", "Szombat"];
$scope.uiConfig.calendar.dayNamesShort = ["Vas", "Hét", "Kedd", "Sze", "Csüt", "Pén", "Szo"];
$scope.changeTo = 'English';
} else {
$scope.uiConfig.calendar.dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
$scope.uiConfig.calendar.dayNamesShort = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
$scope.changeTo = 'Hungarian';
}
};
/* event sources array*/
$scope.eventSources = [$scope.events, $scope.eventSource, $scope.eventsF];
$scope.eventSources2 = [$scope.calEventsExt, $scope.eventsF, $scope.events];
}
You should prefer to use angular-bootstrap-calendar from mattlewis92: https://github.com/mattlewis92/angular-bootstrap-calendar
Use mwl-calendar directive for calendar on your page, and then customize template you want. For ex., if your need to add some callback function on date click, you should alter the month view, adding ng-click on calendarMonthCell template, wherever you want.

How to Rebuild owl carousel on ng-click in angular.js?

I am facing some serious issue, I used owl carousel in angular.js. Its working fine on first time. Later i have a buttons on the same page i want to rebuild the owl carousel on that particular button with new data. here is my controller and html code.
.directive('riskcarousel', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attr) {
if (scope.$last === true) {
var syncPosition = function (event) {
var nav = this;
var body = $('#risk_body').data('owlCarousel');
$timeout(function () {
body.to(nav._current);
scope.setPhaBackgroundColor(nav._current);
}, 1000);
};
//console.log(owlCarousel,"Smartdata");
var owl = $(element.parent()).owlCarousel({
items: 3,
nav: false,
dots: false,
center: true,
responsive: {
0: {
items: 3,
nav: false
},
600: {
items: 3,
nav: false
},
1000: {
items: 3,
nav: false
}
},
onDragged: syncPosition
});
//owl.data().owlCarousel.addItem('<a class="item link center-owl-item" style="background-color: transparent;"></a>', owl.data().owlCarousel.num.items - 1);
//owl.data().owlCarousel.addItem('<a class="item link center-owl-item" style="background-color: transparent;"></a>', owl.data().owlCarousel.num.items - 1);
//owl.data().owlCarousel.reset(owl.data().owlCarousel.num.items-1);
$timeout(function () {
owl.data().owlCarousel.to(0);
//owl.data().owlCarousel.removeItem(owl.data().owlCarousel.num.items-1);
//owl.data().owlCarousel.removeItem(owl.data().owlCarousel.num.items-1);
}, 10);
}
element.on('click', function () {
//$('.owl-item').removeClass('selected-item');
//element.parent().addClass('selected-item');
alert('hello');
var index = element.attr('data-index');
var nav = $('#risk_nav').data('owlCarousel');
var body = $('#risk_body').data('owlCarousel');
$timeout(function () {
nav.to(index);
body.to(index);
scope.setPhaBackgroundColor(index);
}, 10);
});
}
}
})
.directive('riskCarouselBody', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attr) {
if (scope.$last === true) {
var syncPosition = function (event) {
var nav = $('#risk_nav').data('owlCarousel');
var body = this;
$timeout(function () {
nav.to(body._current);
scope.setPhaBackgroundColor(body._current);
}, 10);
};
var owl = $(element.parent()).owlCarousel({
items: 1,
nav: false,
dots: false,
responsive: {
0: {
items: 1,
nav: false
},
600: {
items: 1,
nav: false
},
1000: {
items: 1,
nav: false
}
},
onDragged: syncPosition
});
}
}
}
})
Html code
<div ng-repeat="s_disease in sub_diseases"
style="float: left; border-radius: 50%; height: 50px; width: 50px; margin: 2px;"
ng-class="[s_disease.background , s_disease.class, 'sub_diseases_clicked']">
<img ng-src="http://localhost:3000/uploads/{{s_disease.icon}}" style="width: 50px; height: 50px"
ng-click="getSubDiseasesPHA(s_disease.id) ">
</div>
</div>
<div class="pha-carousel">
<div class="pha-back">
<a class="carousel-icon" href="#/qsummary"><i class="ion-chevron-left"
style="color: rgba(255, 255, 255, 1);"></i></a>
</div>
<div class="owl-carousel" id="risk_nav">
<a class="item link center-owl-item" data-index="{{$index}}" ng-repeat="pha in phas"
ng-class="[pha.background, pha.class]"
ng-style="pha.key_string=='qscore' && {'background-color': pha.background}"
riskcarousel><h1 style="white-space:normal !important;">{{pha.health_area}}</h1></a>
</div>
</div>
I made a carousel initialize function and calls when controller initialize
$scope.initializeCaraousel = function () {
//Check if already carousel made then destroy
if (typeof $("#sync1").data('owlCarousel') != 'undefined') {
$("#sync1").data('owlCarousel').destroy();
$('#sync2').data('owlCarousel').destroy();
}
var sync1 = $("#sync1");
var sync2 = $("#sync2");
sync1.owlCarousel({
singleItem : true,
slideSpeed : 1000,
navigation: true,
pagination:false,
afterAction : syncPosition,
responsiveRefreshRate : 200
});
sync2.owlCarousel({
items : 3,
itemsDesktop : [1199,10],
itemsDesktopSmall : [979,10],
itemsTablet : [768,8],
itemsMobile : [479,4],
pagination:false,
responsiveRefreshRate : 100,
afterInit : function(el){
el.find(".owl-item").eq(0).addClass("synced");
}
});
function syncPosition(el){
var current = this.currentItem;
console.log(current);
$("#sync2")
.find(".owl-item")
.removeClass("synced")
.eq(current)
.addClass("synced")
if($("#sync2").data("owlCarousel") !== undefined){
center(current)
}
// code for smooth transition
this.owl.owlItems.removeClass('smooth-slide');
$(this.owl.owlItems[this.owl.currentItem]).addClass('smooth-slide');
}
$("#sync2").on("click", ".owl-item", function(e){
// e.preventDefault();
var id = $(this).attr("id");
//console.log(id);
var index = parseInt(e.target.id);
//console.log(index);
sync1.trigger("owl.goTo", index);
});
function center(number){
var sync2visible = sync2.data("owlCarousel").owl.visibleItems;
var num = number;
var found = false;
for(var i in sync2visible){
if(num === sync2visible[i]){
var found = true;
}
}
if(found===false){
if(num>sync2visible[sync2visible.length-1]){
sync2.trigger("owl.goTo", num - sync2visible.length+2)
}else{
if(num - 1 === -1){
num = 0;
}
sync2.trigger("owl.goTo", num);
}
} else if(num === sync2visible[sync2visible.length-1]){
sync2.trigger("owl.goTo", sync2visible[1])
} else if(num === sync2visible[0]){
sync2.trigger("owl.goTo", num-1)
}
}
}

What's wrong with loading this JSON?

What's wrong with loading this JSON?
Select a new object, set its ID, add and save it. Trying to reload the JSON object results in an empty canvas.
http://jsfiddle.net/Sugv4/14/
function loadCanvas() {
canvas.clear();
window.alert(js);
canvas.loadFromDatalessJSON(js)
canvas.renderAll();
}
Try put this in Javascript code:
var canvas;
$(function () {
canvas = window._canvas = new fabric.Canvas('c');
fabric.Labeledrect = fabric.util.createClass(fabric.Rect, {
type: 'labeledRect',
initialize: function (options) {
options || (options = {});
this.callSuper('initialize', options);
this.set('label', options.label);
this.set('id', options.id);
},
toObject: function () {
return fabric.util.object.extend(this.callSuper('toObject'), {
label: this.get('label'),
id: this.get('id')
});
},
_render: function (ctx) {
this.callSuper('_render', ctx);
ctx.font = '10px Helvetica';
ctx.fillStyle = '#333';
ctx.fillText(this.label, -this.width / 2, -this.height / 2 + 10);
ctx.fillText(this.id, -this.width / 2, -this.height / 2 + 30);
}
});
fabric.Labeledrect.fromObject = function (object, callback) {
return new fabric.Labeledrect(object);
}
fabric.Labeledrect.async = true;
});
function voegObjectToe() {
var myObjects = document.getElementById("myObjects");
var kenmerk = myObjects.options[myObjects.selectedIndex].text;
//nieuw object
var rect = new fabric.Labeledrect({
left: canvas.width / 2,
top: canvas.height / 2
});
if (kenmerk == 'Camper') {
rect.set({
width: 80,
height: 50,
fill: '#faa',
label: 'Camper',
id: document.getElementById("myObject").value
});
} else if (kenmerk == 'Caravan') {
rect.set({
width: 80,
height: 60,
fill: '#3ac',
label: 'Caravan',
id: document.getElementById("myObject").value
});
} else if (kenmerk == 'Auto') {
rect.set({
width: 70,
height: 40,
fill: '#bbb',
label: 'Auto',
id: document.getElementById("myObject").value
});
} else if (kenmerk == "Boot") {
rect.set({
width: 150,
height: 60,
fill: '#8d1',
label: 'Boot',
id: document.getElementById("myObject").value
});
}
canvas.add(rect);
rect.set({
label: kenmerk + ' ' + rect.width * 7 + ' cm',
rx: 8,
ry: 8
});
canvas.renderAll();
}
function saveCanvas() {
js = JSON.stringify(canvas.toDatalessJSON());
}
function loadCanvas() {
//window.alert(js);
canvas.clear();
canvas.loadFromDatalessJSON(js);
canvas.renderAll();
}