我正在使用angular chart来填充饼图。为了填充图表,我需要在服务中进行$http.get()
调用并从控制器调用服务方法。但如果我拨打$http
电话,图表就无效了。
angular.module('shopAdminApp')
.service('ChartService', ['$http',ChartService])
function ChartService($http) {
this.GetAllChartData = function (month, year) {
return $http.get('GetMonthlyStatistics?month=' + month + '&&year=' + year + '');
}
}
angular.module('shopAdminApp')
.controller('chartCtrl', ["ChartService", ChartCtrl]);
function ChartCtrl(ChartService) {
// this.labels = ["Download Sales", "In-Store Sales", "Mail-Order Sales"];
// this.data = [10, 20, 100];
var promise = ChartService.GetAllChartData(12, 2012);
promise.then(function (response) {
console.log(response.data);
this.chartsdata = response.data;
this.labels = response.data.BranchNames;
this.data = response.data.BranchMonthlyTotalSales;
});
// console.log(this.chartsdata);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<canvas id="pie1" class="chart chart-pie" data="chart.data" labels="chart.labels" height="300" width="400"></canvas>
如果我取消评论评论的部分,饼图工作正常,但我需要使用$http
调用填充值。我怎么能这样做?
答案 0 :(得分:1)
尝试这样:
i
你必须记住function ChartCtrl(ChartService) {
var self = this;
var promise = ChartService.GetAllChartData(12, 2012);
promise.then(function (response) {
self.chartsdata = response.data;
self.labels = response.data.BranchNames;
self.data = response.data.BranchMonthlyTotalSales;
});
}
关键字是指当前的上下文,所以当你在promise中回调函数this
不再指向你的控制器,而是指向回调函数本身。