I'm learning Javascript and AngularJS by integrating two examples: Spring MVC and AngularJS and AngularJS and Highcharts.
This seemingly simple task has puzzled me for a few days:
In the Spring REST-powered backend, I added the class Book with a property "prices", an array of doubles to represent the monthly or yearly prices of the book. The AngularJS client shows the "prices" by adding the following code to html:
<div style="height:300px;width:250px;overflow:auto;float:left;">
<table class="table table-striped">
<tr ng-repeat="price in book.prices">
<td>{{price}}</td>
</tr>
</table>
</div>
and the following code to the controller:
var bookId = $routeParams.bookId;
if (bookId === 'new') {
$scope.book = new Book();
} else {
$scope.book = Book.get({bookId: bookId});
}
The table updates dynamically with the data from the backend. Pretty neat and elegant!
What baffles me is the highcharts part. I added the following to the html:
<div style="border: 1px solid #ccc; width: 620px; float: right">
<highchart id="chart1" config="chartConfig"></highchart>
</div>
and some static values for the "prices" to the controller:
var prices = [60.5, 55.7]; // Static data works
$scope.chartConfig = {
options : {
chart : {
type : 'line'
}
},
series : [ {
data : prices
} ],
title : {
text : 'Monthly Book Prices'
},
loading : false
}
And the hichcharts works fine with AngularJS.
I then tried to update the dynamic "prices" from the backend to the chart by adding some code to the controller:
// var prices = [60.5, 55.7]; // Static data works
var prices = $scope.book.prices
or
// var prices = [60.5, 55.7]; // Static data works
var prices = [$scope.book.prices]
and after some time realized this was a quite naive understanding of AngularJS. I've also followed the way described in
How to produce a highchart (using angular js) with json data coming from an Ajax request without success.
Is there an elegant way like the prices table shown above for the Highcharts to display the dynamic data from backend?
Try changing the data in your chart config directly:
$scope.chartConfig.series[0].data = $scope.book.prices
Or use an object for the series:
var prices = {data: [60.5, 55.7]}; // Static data works
$scope.chartConfig = {
options : {
chart : {
type : 'line'
}
},
series : [ prices ],
title : {
text : 'Monthly Book Prices'
},
loading : false
}
Then later:
prices.data = [60.5, 55.7]
Related
I was working with tables and I came across this issue: I want to access the data-row-key attribute (shown in the image below) in the table header row at a child row and I'm stuck. Code:
class App extends React.Component {
render() {
const columns = [
// sample of how the JSON API is read
{
title: "Title", dataIndex: "title", key: "title",
},
// the one that actually matters. becomes the actions column eventually
{
title: "Action", dataIndex: "", key: "x", width: "12%",
render: () => (
<Popconfirm
placement="topRight"
title="Are you sure to delete this task?"
// retrieve the data here as a parameter into the confirm(n) call
onConfirm={() => confirm(43)} okText="Yes" cancelText="No"
>
<a>delete</a>
</Popconfirm>
)
}
];
return (
<Table columns={columns} dataSource={this.state.data}/>
);
}
}
Right now I have the actual number (43) in there, but I want it to be dynamic as to be able to retrieve the data from the <tr data-row-key=...> tag, shown in the image below.
As a note, there is not a leading id column at the start of the table. The keys are provided through Django's rest framework -- which is in JSON format, in the very last image. Rendered results:
JSON format:
Can anyone please help me? Thanks in advance.
You can use the querySelector for it.
let value = document.querySelector('data-row-key')
I know this is probably a common question but I had issues getting any solutions to work with my use case. I have a calendar widget I have forked on Codepen made using JS. I want to replace the default data with my Firebase database but the JSON structure is different and breaks the Calendar function. My JSON in Firebase is as follows:
{
"Events" : {
"cool event" : {
"calendar" : "Other",
"color" : "yellow",
"date" : "2017-01-13",
"eventName" : "new"
}
},
The original method that the widget received data was as so:
var data = [
{ eventName: 'Lunch Meeting w/ Mark', calendar: 'Work', color: 'orange', date: '2014-02-08' },]
How can I format either my data or modify the function to accept my data structure? Keep in mind, Firebase does not allow a simple array and stores them as objects...
Here is a CodePen: http://codepen.io/Auzy/pen/OWJxqO
One way would be to transform your data to an array of the required format
For example
var firebase = {
"Events" : {
"cool event" : {
"calendar" : "Other",
"color" : "yellow",
"date" : "2017-01-13",
"eventName" : "new"
}
}
};
var data = [];
for(event in firebase.Events){
data.push(firebase.Events[event])
}
console.log(data)
Update
Firebase api is asynchronous, so you need to wait for the data (using the .once('value').then(..)) to return and then transform the data (which you actually do not need since firebase provides an iterator) and then initialize the calendar.
So you need to change your code to
var stuff = firebase.database().ref().child("Events");
var data = [];
stuff.once('value').then(function(snapshot){
snapshot.forEach(function(event){
data.push( event.val() );
})
var calendar = new Calendar('#calendar', data);
});
(and remove the initialization from the bottom of the code as it has been inserted in the callback)
How do I get pagination with ng-table-dynamic and $http working?
HTML specification of the table is
<table class="table-bonds table table-bordered table-hover table-striped"
export-csv="csv"
separator=","
show-filter="true"
ng-table-dynamic="bondsTable.bondsDataParams with bondsTable.bondsDataCols">
<tr ng-repeat="row in $data">
<td class="hand"
ng-repeat="col in $columns">{{::row.node[col.field]}}</td>
</tr>
The table creation code is:
self.bondsDataParams = new NgTableParams({
page: 1, // show first page
count: 5 // count per page
}, {
filterDelay: 0,
total: 0,
getData: function (params) {
return $http(bondsDataRemote).then(function successCallback(response) {
// http://codepen.io/christianacca/pen/mJoGPE for total setting example.
params.total(response.data.nodes.length);
return response.data.nodes;
}, function errorCallback(response) {
});
}
});
AngularJS 1.5.8
This is an excellent directive for pagination have a look at it . It has lots of options and its easy to use.
The main problem was mixing up loading the data via ajax and not supporting the filtering/pagination on the server side of the request.
Either provide all the data up-front so that the table can filter, or fully support the pagination, sorting and filtering on the server side.
Option 1. Load the data before hand. I used this option because my dataset is not that big and it seemed like the easiest way to allow people to use all the permutations of filtering sorting and downloading.
No total value is required here. The data is all loaded.
var Api = $resource('/green-bonds.json');
// Or just load all the data at once to enable in-page filtering, sorting & downloading.
Api.get({page: "1", count: "10000"}).$promise.then(function (data) {
self.bondsDataParams = new NgTableParams({count: 25}, {
dataset: data.results
})
});
Or fully support the lazy loading data API and set total. Uses getData: rather than just setting dataset.
var Api = $resource('/green-bonds.json');
this.bondsDataParams = new NgTableParams({}, {
getData: function (params) {
return Api.get(params.url()).$promise.then(function (data) {
params.total(data.count);
return data.results;
});
}
});
Note 1: By default $resource expects an object .get() for object, .query() for array. Also see isArray:. I didn't get this to work.
Note 2: params.url() provides $resource with the ng-table params. e.g. {page: "1", count: "10"}
I am Integrating HighChart Into my iPhone application. I am using below Javascript file for appearing high chart. Here below URL high chart providing data but I want to remove this URL and want to read my Xcode plist data and shown on chart based on that data.
https://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?
Below My Code
$(function () {
$.getJSON('https://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function (data) {
// Create the chart
$('#container').highcharts('StockChart', {
rangeSelector : {
selected : 1
},
title : {
text : ''
},
navigator : {
enabled : false
},
plotOptions: {
line: {animation: false}
},
series : [{
name : 'AAPL Stock Price',
data : data,
tooltip: {
valueDecimals: 2
}
}]
});
});
});
To load a plist element, you can use the NSDictionary selectors dictionaryWithContentsOfFile: or dictionaryWithContentsOfURL:
More information: NSDictionary reference
#SteaveJobs Solution you are looking is not possible as https://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=? suggests there is a file by name "aapl-c.json" which server will extract json data from and plot graph using StockChartas component.
Which i feel you should look for is some thing similar to Core Plot and its documentation
I'm a beginner with HIGHCHARTS.
I want to start from this example :
http://people.canonical.com/~bradf/media/highstock/examples/basic-line/index.htm
I downloaded the corresponding JSON file :
http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json
And I want to run it locally (and after test it with my own JSON files).
But it doesn't works!
I use the source code of the example, I've just modified the getJSON line.
I have this :
$.getJSON('./data/json/'+ name+'-c.json&callback=?', function(data) { ... }
I think that the issue comes from the callback.
Any ideas?
To make the example working on your local you will have to follow the below steps:
I assume that the json source code you have downloaded from the url http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json is stored in a file data.json
Now as you would have noticed, the json source in the file data.json would be like as below:
?(/* AAPL historical OHLC data from the Google Finance API */
[
/* May 2006 */
[1147651200000,67.79],
[1147737600000,64.98],
[1147824000000,65.26],
[1147910400000,63.18],
.......
....
So now as you would have noticed there are code lines ?(/* AAPL historical OHLC data from the Google Finance API */ and /* May 2006 */ in the json source which are causing the things to go wrong by generating a parse error because the data source with such code lines is not a valid json string.
So you will have to remove each and every such invalid code line from the whole json file to make the things working correctly.
After removing all the invalid line of code your json file should look like:
[
[1147651200000,67.79],
[1147737600000,64.98],
[1147824000000,65.26],
....
...
]
3. Now till this step you are ready with a valid json data source for the Highstock chart, so finally to display the chart you will have to use the code like:
$(function() {
$.getJSON('data.json', function(data) {
// Create the chart
window.chart = new Highcharts.StockChart({
chart : {
renderTo : 'container'
},
rangeSelector : {
selected : 1
},
title : {
text : 'AAPL Stock Price'
},
series : [{
name : 'AAPL',
data : data,
tooltip: {
valueDecimals: 2
}
}]
});
});
});
The whole page source code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/stock/modules/exporting.js"></script>
<script>
$(function() {
$.getJSON('data.json', function(data) {
// Create the chart
window.chart = new Highcharts.StockChart({
chart : {
renderTo : 'container'
},
rangeSelector : {
selected : 1
},
title : {
text : 'AAPL Stock Price'
},
series : [{
name : 'AAPL',
data : data,
tooltip: {
valueDecimals: 2
}
}]
});
});
});
</script>
<body>
<div id="container" style="height: 500px; min-width: 500px"></div>
</body>
&callback=? is normally appended for jsonp which is a technique used for cross domain calls (to other websites for example.)
From what I can see you should try removing it from the call.
In your case:
$.getJSON('./data/json/'+ name+'-c.json, function(data) { ... }