Using the morris.js charts in my angular js app has been a great addition. I decided to convert it into a directive for better organization and functionality:
barchart.js:
angular.module('app_name').directive('barchart', function () {
return {
// necessary for element functionality
restrict: 'AEC',
template: '<div class=chart_div></div>',
replace: true,
// observing and manipulating the DOM
link: function ($scope, element, attrs) {
var data = $scope[attrs.data],
xkey = $scope[attrs.xkey],
ykeys = $scope[attrs.ykeys],
labels = $scope[attrs.labels];
Morris.Bar({
element: element,
data: data,
xkey: xkey,
ykeys: ykeys,
labels: labels,
hideHover: true,
grid: false
});
}
};
});
Later on, within my page.html, I implemented the directive like this:
<section class="graphs" ng-controller="ChartController">
<div class="graphs_box">
<div class="graphs_box_title">My Orders</div>
<div class="chart_bg">
<div barchart xkey="xkey" ykeys="ykeys" labels="labels" data="MyData"></div>
</div>
</div>
The issue arises when attempting to add data to the chart in 'ChartController' like so:
getChartData = function () {
$scope.xkey = 'X';
$scope.ykeys = ['Y'];
$scope.labels = ['Total Tasks', 'Out of Budget Tasks'];
$scope.PlannedChart = [
{ range: 'A', total_tasks: 20 },
{ range: 'B', total_tasks: 35 },
{ range: 'C', total_tasks: 100 },
{ range: 'D', total_tasks: 50 }
];
};
Everything works perfectly fine this way. However, when trying to load data from a database (in json format) like this:
getChartData = function () {
ChartsService.getCharts("orders").success(function (data) {
$scope.xkey = 'X';
$scope.ykeys = 'Y';
$scope.labels = ['Total Tasks', 'Out of Budget Tasks'];
$scope.OrdersChart = data.Val_Chart;
});
};
It doesn't seem to work as expected. Despite successfully fetching the data from the database (as confirmed during debugging), the code seems to first pass through barchart.js with 'undefined' data before reaching the service that retrieves the data.