Currently, I am in the process of developing a webpage that utilizes Highcharts to display some data. To ensure reusability, I have encapsulated the desired chart within a directive.
'use strict';
angular.module('statisticsApp')
.directive('cleanbarchart', function () {
scope:{
localdata:'@'
}
return {
template: '<div></div>',
restrict: 'E',
link: function postLink(scope, element, iAttrs) {
// console.log(iAttrs);
// console.log(iAttrs);
// var attrs = JSON.parse(iAttrs.id);
var attrs = iAttrs;
element.highcharts({
chart: {
type: 'column',
width:1000,
zoomType: 'x'
},
title: {
text: scope.localdata[attrs.id].title //title
},
xAxis: {
categories: scope.localdata[attrs.id].categories, crosshair: true
},
yAxis: {
min: 0
},
tooltip: {
// code for tooltips
},
plotOptions: {
// additional options
},
series: scope.localdata[attrs.id].series
})
}
};
});
Within my controller, I utilize a service along with a callback function to populate the localdata.
angular.module('statisticsApp')
.controller('AboutCtrl', function ($scope, HttpDataService) {
function done(data){
console.log(data);
$scope.localdata['test2'] = data; //HttpDataService.getUniqueUsers() ;
}
$scope.localdata = {} ;
HttpDataService.getUniqueUsers(done) ;
});
The service structure is as follows:
angular.module('statisticsApp')
.service('HttpDataService', function($http, $q, baseRestPath) {
// AngularJS will instantiate a singleton by calling "new" on this function
return {
getUniqueUsers: function (callback, periodicity) {
var url = baseRestPath + '/sessions/uniqueUsers';
console.log(url);
var dates = [];
var values = [];
$http.get(url).then(
function successCallback(response){
var data = response.data;
data.forEach(function(dataLine) {
dates.push(dataLine[1]);
values.push(dataLine[0]);
})
console.log(values);
callback({title: 'Unique Users', categories:dates, 'series': [ {name: 'Alltime', data:values} ] });
},function errorCallBack(response){
//do nothing
}
);
// returns data
}
}
});
To call the directive in my HTML, I use the following snippet:
<cleanbarchart id="test2"></cleanbarchart>
Even though the service functions correctly and returns the data appropriately, I encounter an error message:
Cannot read property 'title' of undefined
This issue potentially stems from the asynchronous nature of $http requests. Despite attempting to use the watch block to monitor either scope.localdata or scope.localdata[attrs.id], I have been unable to resolve this issue.
link: function postLink(scope, element, iAttrs) {
scope.$watch('localdata',function(){
element.highcharts.....
}
}
or
link: function postLink(scope, element, iAttrs) {
scope.$watch('localdata[' + attrs.id + ']',function(){
element.highcharts.....
}
}
Your assistance with resolving this matter would be greatly appreciated.