I am making a request to a rethinkdb database, grabbing the info and doing a couple manipulations to it so that I have the information I need, and then populating a line chart with data. I am using the angular-chart.js directive, and my issue is that I need to basically re-render the chart after the data manipulations complete. Is there a way that I can do this with a watcher?
$scope.things = [];
$scope.chartData = ChartService.getAll();
setTimeout(function() {
var length = $scope.chartData.$$state.value.data.length;
for (var i = 0; i < length; i++) {
$scope.things[i] = angular.copy($scope.chartData.$$state.value.data[i].State);
}
console.log("Things: " + $scope.things);
var object = {};
var array = $scope.things;
for (var i = 0, j = array.length; i < j; i++) {
object[array[i]] = (object[array[i]] || 0) + 1;
}
console.log("Object: " + JSON.stringify(object));
$scope.labels = [object];
console.log("Labels: " + $scope.labels);
}, 2000);
So I create an empty array, then make a call to my service and push the data I get back into the array. Then I run a for loop on it to add the number of each array element (in this case I am getting back different state abbreviations) to an object. The object looks something like {"AZ": 1, "OH": 5, etc....}. Basically then I need the graph to re-render at this point with the new data. I assumed a watcher would be the answer but any suggestions are welcome. Thanks!
I would make the ChartService return a promise. This will let you do your manipulations/rendering after you get your data.
var app = angular.module('plunker', []);
app.controller('ChartController', function($scope, ChartService) {
ChartService.getAll().success(function(chartData) {
$scope.chartData = chartData;
// do you data manipulations here
// call your chart renderer here
});
});
app.factory("ChartService", function($http) {
var service = {};
service.getAll = function() {
return $http.get("api/states").success(function(states) {
// do some stuff
})
}
return service;
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.