Could somebody explain (find error) in my code please. 'cssSelector' for example 'a[href="#"]' Thank you very much!
I tried to fire different events: 'touchstart', 'touchmove', 'touchend' and nothing... in fact I just need reaction on a click event on Mobile Devices (simulators) on BrowserStack.com
I use this API: Nightwatch.js API Reference | .execute()
My function:
function touchClick(selector, callBackFunc) {
client.execute(function (cssSelector, callBackFunc) {
try {
console.log("touch: ", cssSelector);
var evt = this.document.createEvent('TouchEvent');
evt.initEvent("touchend", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); //initUIEvent
//evt.initUIEvent('touchstart', true, true);
// evt.view = window;
//evt.altKey = false;
// evt.ctrlKey = false;
// evt.shiftKey = false;
// evt.metaKey = false;
var elements = document.querySelectorAll(cssSelector);
for (var i = 0; i < elements.length; ++i) {
elements[i].dispatchEvent(evt);
}
} catch (except) {
console.log(except);
}
return evt;
}, selector, callBackFunc);
}
Use:
client.verify.elementPresent('cssSelector'); //OK
//TOUCH CLICK:
touchClick('cssSelector', function (result) {
console.log("TouchClick : * * * * * * * * * * * * ----->")
console.log(result); //...initTouchEvent: 'function initTouchEvent() {\n [native code]\n}'...
client.pause(5000);
})
And a usual click:
//USUAL CLICK WITH CALLBACK:
client.click('cssSelector', function (result) {
this.verify.equal(result.state, 'success'); //OK
console.log('Usual click : ...')
})
Another version of TouchEvent:
client.execute(function (el) {
var node = document.querySelector(el)
var type = 'touchmove'; // touchstart, touchmove, touchend
node.addEventListener(type, function(event) {} , true);
var event = document.createEvent('Event');
event.initEvent(type, true, true);
event.constructor.name;
node.dispatchEvent(event);
return event; // *********** ANCHOR: LINE 100500 **********
}, ['a[href="#menu"]'], function (result) {
if (result.status !== -1) {
console.log('[100500] * TOUCH MOVE ON MOBILE MENU');
client.pause(500);
console.log(result)
}
})
Which produces output:
[100500] * TOUCH MOVE ON MOBILE MENU
{ status: 0,
value:
{ clipboardData: null,
type: 'touchmove',
target: { ELEMENT: ':wdc:XXXXXXXXX' },
currentTarget: null,
eventPhase: 0,
bubbles: true,
cancelable: true,
timeStamp: 1499849859209,
defaultPrevented: true,
srcElement: { ELEMENT: ':wdc:XXXXXXXXX' },
returnValue: false,
cancelBubble: false,
NONE: 0,
CAPTURING_PHASE: 1,
AT_TARGET: 2,
BUBBLING_PHASE: 3,
MOUSEDOWN: 1,
MOUSEUP: 2,
MOUSEOVER: 4,
MOUSEOUT: 8,
MOUSEMOVE: 16,
MOUSEDRAG: 32,
CLICK: 64,
DBLCLICK: 128,
KEYDOWN: 256,
KEYUP: 512,
KEYPRESS: 1024,
DRAGDROP: 2048,
FOCUS: 4096,
BLUR: 8192,
SELECT: 16384,
CHANGE: 32768,
stopPropagation: 'function stopPropagation() {\n [native code]\n}',
preventDefault: 'function preventDefault() {\n [native code]\n}',
initEvent: 'function initEvent() {\n [native code]\n}',
stopImmediatePropagation: 'function stopImmediatePropagation() {\n [native code]\n}' },
sessionId: 'XXXXXXXXXX' }
NEXT CODE:
browser.execute(function (el) {
var node = document.querySelector(el)
//node.addEventListener("click", function (event) { }, false);
var evt = document.createEvent("MouseEvent");
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
node.dispatchEvent(evt);
return evt; // ******************** ANCHOR: LINE 100500 ********************
}, ['a[href="#menu"]'], function (result) {
if (result.status !== -1) {
console.log(purpleColor('[100500] * TOUCH MOVE ON MOBILE MENU '));
browser.pause(500);
console.log(result) //LOCAL OUTPUT
}
})
LOCAL OUTPUT:
[100500] * TOUCH MOVE ON MOBILE MENU ----------------------->
{ status: 0,
value:
{ clipboardData: null,
screenX: 0,
screenY: 0,
clientX: 0,
clientY: 0,
ctrlKey: false,
shiftKey: false,
altKey: false,
metaKey: false,
button: 0,
relatedTarget: null,
webkitForce: 0,
offsetX: -319,
offsetY: -18,
x: 0,
y: 0,
fromElement: null,
toElement: { ELEMENT: ':wdc:111111111111' },
dataTransfer: null,
WEBKIT_FORCE_AT_MOUSE_DOWN: 1,
WEBKIT_FORCE_AT_FORCE_MOUSE_DOWN: 2,
initMouseEvent: 'function initMouseEvent() {\n [native code]\n}',
view: { WINDOW: ':wdc:111111111111' },
detail: 0,
keyCode: 0,
charCode: 0,
layerX: -319,
layerY: -37,
pageX: 0,
pageY: 0,
which: 1,
initUIEvent: 'function initUIEvent() {\n [native code]\n}',
type: 'click',
target: { ELEMENT: ':wdc:111111111111' },
currentTarget: null,
eventPhase: 0,
bubbles: true,
cancelable: true,
timeStamp: 1699192969041,
defaultPrevented: false,
srcElement: { ELEMENT: ':wdc:111111111111' },
returnValue: true,
cancelBubble: false,
NONE: 0,
CAPTURING_PHASE: 1,
AT_TARGET: 2,
BUBBLING_PHASE: 3,
MOUSEDOWN: 1,
MOUSEUP: 2,
MOUSEOVER: 4,
MOUSEOUT: 8,
MOUSEMOVE: 16,
MOUSEDRAG: 32,
CLICK: 64,
DBLCLICK: 128,
KEYDOWN: 256,
KEYUP: 512,
KEYPRESS: 1024,
DRAGDROP: 2048,
FOCUS: 4096,
BLUR: 8192,
SELECT: 16384,
CHANGE: 32768,
stopPropagation: 'function stopPropagation() {\n [native code]\n}',
preventDefault: 'function preventDefault() {\n [native code]\n}',
initEvent: 'function initEvent() {\n [native code]\n}',
stopImmediatePropagation: 'function stopImmediatePropagation() {\n [native code]\n}' },
sessionId: 'aaaaaaaaaaaaaaaaaa' }
And I still can't click on Mobile device!
Sorry, following test has shown that clicks work fine on Mobile Devices. Some error occurred only on our website... Now I do investigation. Thank you, Google!
const TEST_NAME = 'Click Event on Mobile: ';
//var expect = require('chai').expect;
var exports = module.exports = {};
function test(browser) {
//TEST GOOGLE.CO.UK
browser.url('https://www.google.co.uk')
.waitForElementVisible('body', 2000)
.maximizeWindow()
.setValue('input[type="search"]', 'nightwatch')
.pause(1000)
browser.getValue('input[type="search"]', function (result) {
this.verify.equal(result.state, 'nightwatch');
});
browser.click('button#tsbb[type="submit"]', function (result) {
this.verify.strictEqual(result.status, 0);
})
browser.pause(2000)
browser.end();
}
exports[TEST_NAME] = function (browser) { test(browser) }
Related
I am trying to integrate highcharts sparkline with angular ui-grid directive but unable to plot the sparkline. When we try to dynamically plot the sparklines using ui-grid nothing gets plotted. I have made necessary changes to the sparkline code as well yet unable to find what is the issue. We need age column to have highcharts sparkline. Any pointer will be of great help.
$scope.gridOptions = {
enableFiltering: false,
enableSorting: true,
}
$scope.gridOptions.columnDefs = [{
name: 'id'
}, {
name: 'name'
}, {
name: 'age',
cellTemplate: '<div id="table-sparkline" data-sparkline="71, 78, 39, 66"></div>'
}, {
name: 'address.city'
}];
$http.get('https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/500_complex.json')
.success(function(data) {
$scope.gridOptions.data = data;
console.log(JSON.stringify(data));
/**
* Create a constructor for sparklines that takes some sensible defaults and merges in the individual
* chart options. This function is also available from the jQuery plugin as $(element).highcharts('SparkLine').
*/
Highcharts.SparkLine = function(a, b, c) {
var hasRenderToArg = typeof a === 'string' || a.nodeName,
options = arguments[hasRenderToArg ? 1 : 0],
defaultOptions = {
chart: {
renderTo: (options.chart && options.chart.renderTo) || this,
backgroundColor: null,
borderWidth: 0,
type: 'area',
margin: [2, 0, 2, 0],
width: 120,
height: 20,
style: {
overflow: 'visible'
},
// small optimalization, saves 1-2 ms each sparkline
skipClone: true
},
title: {
text: ''
},
credits: {
enabled: false
},
xAxis: {
labels: {
enabled: false
},
title: {
text: null
},
startOnTick: false,
endOnTick: false,
tickPositions: []
},
yAxis: {
endOnTick: false,
startOnTick: false,
labels: {
enabled: false
},
title: {
text: null
},
tickPositions: [0]
},
legend: {
enabled: false
},
tooltip: {
backgroundColor: null,
borderWidth: 0,
shadow: false,
useHTML: true,
hideDelay: 0,
shared: true,
padding: 0,
positioner: function(w, h, point) {
return {
x: point.plotX - w / 2,
y: point.plotY - h
};
}
},
plotOptions: {
series: {
animation: false,
lineWidth: 1,
shadow: false,
states: {
hover: {
lineWidth: 1
}
},
marker: {
radius: 1,
states: {
hover: {
radius: 2
}
}
},
fillOpacity: 0.25
},
column: {
negativeColor: '#910000',
borderColor: 'silver'
}
}
};
options = Highcharts.merge(defaultOptions, options);
return hasRenderToArg ?
new Highcharts.Chart(a, options, c) :
new Highcharts.Chart(options, b);
};
var start = +new Date(),
$tds = $('div[data-sparkline]'),
fullLen = $tds.length,
n = 0;
// Creating 153 sparkline charts is quite fast in modern browsers, but IE8 and mobile
// can take some seconds, so we split the input into chunks and apply them in timeouts
// in order avoid locking up the browser process and allow interaction.
function doChunk() {
var time = +new Date(),
i,
len = $tds.length,
$td,
stringdata,
arr,
data,
chart;
for (i = 0; i < len; i += 1) {
$td = $($tds[i]);
stringdata = $td.data('sparkline');
arr = stringdata.split('; ');
data = $.map(arr[0].split(', '), parseFloat);
chart = {};
if (arr[1]) {
chart.type = arr[1];
}
$td.highcharts('SparkLine', {
series: [{
data: data,
pointStart: 1
}],
tooltip: {
headerFormat: '<span style="font-size: 10px">' + $td.parent().find('div').html() + ', Q{point.x}:</span><br/>',
pointFormat: '<b>{point.y}.000</b> USD'
},
chart: chart
});
n += 1;
// If the process takes too much time, run a timeout to allow interaction with the browser
if (new Date() - time > 500) {
$tds.splice(0, i + 1);
setTimeout(doChunk, 0);
break;
}
}
}
doChunk();
Plunker
I am trying to integrate spark line high chart in Angularjs nested UI grid. I have implemented Highcharts.SparkLine function within row expand event in UI grid. Is there any function like rowExpandComplete in Angular UiGrid?
gridApi.expandable.on.rowExpandedStateChanged($scope, function (row) {
if (row.isExpanded) {
var str = "10,12,45,34";
$scope.template = "<table id='table-sparkline'><tbody id='tbody-sparkline'><tr><td data-sparkline=" + str + "> </td> </tr> </tbody></table>";
row.entity.subGridOptions = {
columnDefs: [
{ name: 'name' },
{ name: 'gender', cellTemplate: $scope.template },
{ name: 'company' }
]
};
$http.get('https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/100.json')
.success(function (data) {
row.entity.subGridOptions.data = data;
/**
* Create a constructor for sparklines that takes some sensible defaults and merges in the individual
* chart options. This function is also available from the jQuery plugin as $(element).highcharts('SparkLine').
*/
Highcharts.SparkLine = function (a, b, c) {
var hasRenderToArg = typeof a === 'string' || a.nodeName,
options = arguments[hasRenderToArg ? 1 : 0],
defaultOptions = {
chart: {
renderTo: (options.chart && options.chart.renderTo) || this,
backgroundColor: null,
borderWidth: 0,
type: 'area',
margin: [2, 0, 2, 0],
width: 120,
height: 20,
style: {
overflow: 'visible'
},
// small optimalization, saves 1-2 ms each sparkline
skipClone: true
},
title: {
text: ''
},
credits: {
enabled: false
},
xAxis: {
labels: {
enabled: false
},
title: {
text: null
},
startOnTick: false,
endOnTick: false,
tickPositions: []
},
yAxis: {
endOnTick: false,
startOnTick: false,
labels: {
enabled: false
},
title: {
text: null
},
tickPositions: [0]
},
legend: {
enabled: false
},
tooltip: {
backgroundColor: null,
borderWidth: 0,
shadow: false,
useHTML: true,
hideDelay: 0,
shared: true,
padding: 0,
positioner: function (w, h, point) {
return { x: point.plotX - w / 2, y: point.plotY - h };
}
},
plotOptions: {
series: {
animation: false,
lineWidth: 1,
shadow: false,
states: {
hover: {
lineWidth: 1
}
},
marker: {
radius: 1,
states: {
hover: {
radius: 2
}
}
},
fillOpacity: 0.25
},
column: {
negativeColor: '#910000',
borderColor: 'silver'
}
}
};
options = Highcharts.merge(defaultOptions, options);
return hasRenderToArg ?
new Highcharts.Chart(a, options, c) :
new Highcharts.Chart(options, b);
};
var start = +new Date(),
$tds = $('td[data-sparkline]'),
fullLen = $tds.length,
n = 0;
// Creating 153 sparkline charts is quite fast in modern browsers, but IE8 and mobile
// can take some seconds, so we split the input into chunks and apply them in timeouts
// in order avoid locking up the browser process and allow interaction.
function doChunk() {
var time = +new Date(),
i,
len = $tds.length,
$td,
stringdata,
arr,
data,
chart;
for (i = 0; i < len; i += 1) {
$td = $($tds[i]);
stringdata = $td.data('sparkline');
arr = stringdata.split('; ');
data = $.map(arr[0].split(', '), parseFloat);
chart = {};
if (arr[1]) {
chart.type = arr[1];
}
$td.highcharts('SparkLine', {
series: [{
data: data,
pointStart: 1
}],
tooltip: {
headerFormat: '<span style="font-size: 10px">' + $td.parent().find('th').html() + ', Q{point.x}:</span><br/>',
pointFormat: '<b>{point.y}.000</b> USD'
},
chart: chart
});
n += 1;
// If the process takes too much time, run a timeout to allow interaction with the browser
if (new Date() - time > 500) {
$tds.splice(0, i + 1);
setTimeout(doChunk, 0);
break;
}
// Print a feedback on the performance
if (n === fullLen) {
$('#result').html('Generated ' + fullLen + ' sparklines in ' + (new Date() - start) + ' ms');
}
}
}
doChunk();
});
}
});
But it is triggering only for second time when we expand the row. Can any one tell me where I am going wrong. I have created the plunker for the same.
Learning AngularJS and HighCharts.
[Plunker Link][1]
I would like to understand how I can get the data from a JSON object and dynamically update the values on the x-axis and the bar chart value. The Y-axis values are constant.
Right now I have hard coded the values, I want the x-axis and bar chart values from the backend.
Here is what I have tried -
(function() {
'use strict';
angular.module('myModule', [])
// Directive for generic chart, pass in chart options
.directive('hcChart', function() {
return {
restrict: 'E',
template: '<div></div>',
scope: {
options: '='
},
link: function(scope, element) {
Highcharts.chart(element[0], scope.options);
}
};
})
.controller('MainCtrl', function($scope, $http) {
$scope.chartData = [];
$scope.totalCostList = [];
loadChartData();
function loadChartData() {
var httpRequest = $http({
method: 'GET',
url: './example.json'
}).then(function(response) {
console.log(response.data);
$scope.chartData = response.data;
console.log("length:" + $scope.chartData.activityResponse.length);
for (var i = 0; i < $scope.chartData.activityResponse.length; i++) {
$scope.totalCostList.push(parseInt($scope.chartData.activityResponse[i].totalCost));
}
console.log($scope.totalCostList);
});
}
//var chartData = $scope.totalCostList;
var yAxisLabels = [1, 5000, 10000, 15000, 20000];
var chartData = [
10000, 5000, 4000, 15000, 16000, 10000, 5000, 4000, 15000, 2000,
10000, 5000, 4000, 15000, 16000, 10000, 5000, 4000, 15000, 2000,
10000, 5000, 4000, 15000, 16000, 10000, 5000, 4000, 15000, 2000,
10000, 5000, 4000, 15000, 16000, 10000, 5000, 4000, 15000, 2000,
10000, 5000, 4000, 15000, 16000, 10000, 5000, 4000, 15000, 2000,
10000, 5000
];
var dateLine = Date.UTC(2015, 0, 1);
Highcharts.getOptions().colors[0] = {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, '#6EB7D8'],
[0.4, '#2989D8'],
[0.7, '#207cca'],
[1, '#1E5799']
]
};
Highcharts.setOptions({
lang: {
thousandsSep: ','
}
});
//To give the chart a bounce effect
Math.easeOutBounce = function(pos) {
if ((pos) < (1 / 2.75)) {
return (7.5625 * pos * pos);
}
if (pos < (2 / 2.75)) {
return (7.5625 * (pos -= (1.5 / 2.75)) * pos + 0.75);
}
if (pos < (2.5 / 2.75)) {
return (7.5625 * (pos -= (2.25 / 2.75)) * pos + 0.9375);
}
return (7.5625 * (pos -= (2.625 / 2.75)) * pos + 0.984375);
};
$scope.chartOptions = {
chart: {
type: 'column',
margin: [70, 30, 30, 80]
},
exporting: {
enabled: false
},
credits: {
enabled: false
},
legend: {
enabled: false
},
title: {
text: 'Weekly Inventory at Cost',
style: {
color: '#333'
},
align: 'left',
x: 10,
y: 20
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
month: '%b'
},
lineColor: '#333',
tickColor: '#333',
crosshair: true,
startOnTick: false,
endOnTick: false,
minPadding: 0,
maxPadding: 0,
tickmarkPlacement: 'on',
labels: {
align: 'left',
rotation: 0
}
},
yAxis: {
crosshair: true,
lineColor: '#333',
tickColor: '#333',
tickPositioner: function() {
return yAxisLabels;
},
labels: {
format: '{value:,.0f}'
},
title: {
enabled: false
},
lineWidth: 1,
tickWidth: 1,
id: 'cost',
gridLineWidth: 0,
min: 1
},
plotOptions: {
column: {
pointPadding: 0.1,
borderWidth: 0,
pointPlacement: 'between'
}
},
shadow: true,
series: [{
data: chartData,
pointStart: dateLine,
pointInterval: 7 * 24 * 3600 * 1000 // 7days
}]
};
});
})();
<!DOCTYPE html>
<html ng-app="myModule">
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="MainCtrl">
<hc-chart options="chartOptions" style="width: 96%; height: 300px;">Placeholder for generic chart</hc-chart>
</body>
</html>
My example JSON -
{"message": "success",
"status": "OK",
"activityResponse": [{
"storeNo": "00208",
"wk": "1",
"year": "2016",
"totalCost": "349622.9"
},{
"storeNo": "00208",
"wk": "2",
"year": "2016",
"totalCost": "2000"
},
{
"storeNo": "00208",
"wk": "3",
"year": "2016",
"totalCost": "15000"
}]
}
Here is an approach to adding to the x-axis categories and updating the category values. Grab a reference to the chart's series when the chart is created.
var series = this.series[0];
Then, when there is an update to the data, make the following call.
series.setData(seriesDataSource, true, true, false);
I have adapted your Plunker to show an example of the chart with series records being added and updated.
https://embed.plnkr.co/SWGuRTyTM3AU6yhptYvM/
I am working on Angular/ionic Cordova project. I am using google.visualization.LineChart to display the chart in my project. First time when we come on the page where I have draw the chart, It is working properly. But when I further navigate to next ion-view and came back to the screen where I have drawn the chart, chart does not appear. Any idea why it is happening? here is my code:
$scope.$on('$ionicView.enter', function() {
$ionicLoading.show({
template: '<ion-spinner icon="spiral"></ion-spinner>',
noBackdrop:false
});
serverRepo.salesMonthly().then(function(objS){
$scope.monthlyData=objS.data;
if(objS.data.orders == null){
$ionicLoading.hide();
alert('There is not data regarding Monthly Sale');
}else{
angular.forEach(objS.data.orders, function(value, key) {
objS.data.orders[key].CreatedOn=new Date(objS.data.orders[key].CreatedOn);
if(key == objS.data.orders.length-1){
$scope.data = objS.data;
drawChart();
console.log('drawChart Called');
}
})
$ionicLoading.hide();
}
},function(objE){
console.log("Error:-\n"+JSON.stringify(objE));
$ionicLoading.hide();
});
});
function drawChart(){
var options = {
legend: { position: 'bottom' },
curveType: 'function',
titlePosition: 'in',
axisTitlesPosition: 'in',
hAxis: {
textPosition: 'in',
minValue: 0,
textStyle:{color: "#fff"}
},
vAxis: {
minValue: 0,
maxValue: 13,
textPosition: 'in',
textStyle:{color: "#fff"},
minorGridlines:{color: "#ccc"}
},
lineWidth: 6,
fontSize:11,
chartArea:{left:0,top:0,width: '100%', height: '100%',backgroundColor: '#43396D'},
colors: ['#32BD76'],
animation:{
duration: 1500,
easing: 'out',
startup: true
}
};
google.charts.setOnLoadCallback( function () {
// Create and populate the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'labels');
data.addColumn('number', 'data');
for(i = 0; i < $scope.data.labels.length; i++)
data.addRow([$scope.data.labels[i], $scope.data.datasets.data[i]]);
// Create and draw the visualization.
$scope.myChart=new google.visualization.LineChart(document.getElementById('curve_chartmonthly'));
$scope.myChart.draw(data, options);
console.log('chart drawn.......');
});
}
think the problem has to do with google.charts.setOnLoadCallback
which is called once per page load
try moving the code inside the callback to drawChart
then call drawChart from the callback
see following example...
$scope.$on('$ionicView.enter', function() {
$ionicLoading.show({
template: '<ion-spinner icon="spiral"></ion-spinner>',
noBackdrop:false
});
serverRepo.salesMonthly().then(function(objS){
$scope.monthlyData=objS.data;
if(objS.data.orders == null){
$ionicLoading.hide();
alert('There is not data regarding Monthly Sale');
}else{
angular.forEach(objS.data.orders, function(value, key) {
objS.data.orders[key].CreatedOn=new Date(objS.data.orders[key].CreatedOn);
if(key == objS.data.orders.length-1){
$scope.data = objS.data;
drawChart();
console.log('drawChart Called');
}
})
$ionicLoading.hide();
}
},function(objE){
console.log("Error:-\n"+JSON.stringify(objE));
$ionicLoading.hide();
});
});
function drawChart(){
var options = {
legend: { position: 'bottom' },
curveType: 'function',
titlePosition: 'in',
axisTitlesPosition: 'in',
hAxis: {
textPosition: 'in',
minValue: 0,
textStyle:{color: "#fff"}
},
vAxis: {
minValue: 0,
maxValue: 13,
textPosition: 'in',
textStyle:{color: "#fff"},
minorGridlines:{color: "#ccc"}
},
lineWidth: 6,
fontSize:11,
chartArea:{left:0,top:0,width: '100%', height: '100%',backgroundColor: '#43396D'},
colors: ['#32BD76'],
animation:{
duration: 1500,
easing: 'out',
startup: true
}
};
// Create and populate the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'labels');
data.addColumn('number', 'data');
for(i = 0; i < $scope.data.labels.length; i++)
data.addRow([$scope.data.labels[i], $scope.data.datasets.data[i]]);
// Create and draw the visualization.
$scope.myChart=new google.visualization.LineChart(document.getElementById('curve_chartmonthly'));
$scope.myChart.draw(data, options);
console.log('chart drawn.......');
}
google.charts.setOnLoadCallback(drawChart);
I have the same problem. I resolve change the ID reference for a class.
Ex:
to
After, identify the element with jquery:
from document.getElementById('your_chart_id') to $('.your_chart_id')[0]
I'm trying to call a function of my directive in my controller. I would like to reshape a curve. At the moment, I can do within the Directive. But I need to outsource the call. Do you know how can I proceed?
My directive :
.directive('drawCharts', function () {
return function (scope, element, attrs) {
scope.$watch('curveArray', function () {
drawPlot();
}, true);
var drawPlot = function () {
/* Define var for interactive chart */
var tickInterval = scope.intervalMillisecond;
var typeLine = 'line';
var chart = function (curveArrayShow, typeLine, optionLineBool, yAxisCurveArrayShow, pointStart, pointEnd) {
var optionLine = { dataLabels: { enabled: optionLineBool, y: -20 }};
new Highcharts.Chart({
chart: {
pinchType: 'x',
renderTo: 'container',
type: typeLine,
backgroundColor:'rgba(255, 255, 255, 0.95)',
events: {
load: function(event) {
//alert ('Chart loaded : ' + event);
//scope.isLoading = false;
}
}
},
legend: {
enabled: false
},
title: {
text: ''
},
xAxis: [{
type: 'datetime',
labels: {
format: '{value: <b>%d/%m</b> %H:%M}',
staggerLines: 1
},
opposite: true,
plotLines: [{
color: '#FF0000', // Red
width: 2,
value: new Date().getTime() // Position, you'll have to translate this to the values on your x axis
}],
min: pointStart,
max: pointEnd,
minPadding: 0,
maxPadding: 0,
startOnTick: false, // allow to start not from tick
endOnTick: false,
tickInterval: tickInterval
}],
yAxis: yAxisCurveArrayShow,
tooltip: {
style:{ zindex: 10 },
xDateFormat: '%d/%m %H:%M',
shared: true,
},
plotOptions: {
column: { borderWidth: 1, borderColor: '#000000' },
spline: {
marker: {
radius: 4,
lineColor: '#666666',
lineWidth: 1
}
},
series: {
dataLabels: {
enabled: optionLineBool,
style: {font: 'bold 11px Arial', textShadow: '0 0 3px white, 0 0 3px white'}
},
marker: {
lineColor: null,
radius: 6,
states: {
hover: {
radius: 10
}
}
}
},
line: optionLine
},
series: curveArrayShow
}}
var pointStart = scope.intervalResearchTime.startDateTime + scope.intervalMillisecond; //remove padding that adding for serie type column
var pointEnd = scope.intervalResearchTime.endDateTime - scope.intervalMillisecond; //remove padding that adding for serie type column
chart(scope.curveArray, typeLine, false, scope.yAxisCurveArray, pointStart, pointEnd);
}
};
In my controller i need to update my chart. So i would like to call the function :
$scope.redrawCurve = function(_index) {
/* My algorithm ...... */
chart(curveArrayShow, typeLine, false, $scope.yAxisCurveArray, pointStart, pointEnd);
};
Thx,
Alex
My suggestion is to use event to notify the directive to redraw the plot, like this:
Controller:
$scope.redrawCurve = function(_index) {
/* My algorithm ...... */
$scope.$broadcast('redraw', arg1, arg2, /* other necessary arguments */);
};
Directive:
scope.$on('redraw', function(arg1, arg2, /* other necessary arguments */) {
drawPlot();
});