这就是我设置JS的方式:
基本上我有一个页面,在该页面上有一个图表。我希望在加载图表数据时显示加载微调器。
angular.module('myApp', [])
.service('chartService', ['$http', function($http) {
var svc = {};
svc.updateChartData = function($scope) {
$scope.loading = true;
$http({method: 'GET', url: 'http://example.com/getjson'})
.success(function(response) {
var data = google.visualization.arrayToDataTable(JSON.parse(response));
var options = {
...
};
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
$scope.loading = false;
});
}
return svc;
}])
.controller('PageController', ['$scope', '$http', 'chartService', function($scope, $http, chartService) {
$scope.loading = true;
// When select option changes
$scope.updateData = function() {
chartService.updateChartData($scope);
};
}])
.controller('ChartController', ['$scope', '$http', 'chartService', function($scope, $http, chartService) {
// On load
chartService.updateChartData($scope);
}]);
我正在使用ng-hide="loading"
和`ng-show =“loading”来确保微调器和图表在正确的时间显示。
但是,我注意到// On load
下面的调用 - 实际上并没有将loading
变为false。关于SO的另一条消息表明,有一种更好的方法可以实现这一目标,而不是通过$scope
,所以任何建议都会受到赞赏。谢谢。
答案 0 :(得分:1)
将范围对象传递给服务并不是一个好习惯,服务意味着无状态。而是利用$http
:
chartService.updateChartData().finally(function(){
$scope.loading = false;
});
而且,正如Grundy在下面提到的那样,请从您的服务中返回$http
以启用回调:
svc.updateChartData = function($scope) {
return $http({ //.. the options });
}
我看到了一些更糟糕的做法。您不应该从服务中将数据添加到DOM,而是还要使用回调:
svc.updateChartData = function($scope) {
return $http({method: 'GET', url: 'http://example.com/getjson'});
}
控制器:
// When select option changes
$scope.updateData = function() {
chartService.updateChartData().then(function(data) {
// success
// do something with the return data from the http call
}, function (error) {
// error
// handle error
}).finally (function() {
// always
$scope.loading = false;
});
};
对于你的谷歌图表,最有必要创建一个指令。
答案 1 :(得分:0)
首先,你有两个控制器,我假设它们是嵌套关系。 PageController包括ChartController。 您想要更改子控制器中父控制器的值。 您必须使用引用类型而不是值类型。
$scope.loading =true;
更改为
$scope.loading ={status:true};
如果你想设置false,应该是
$scope.loading.status =false;
不是
$scope.loading ={status:false};
第二,您可以将回调函数传递给服务。 像这样
svc.updateChartData = function(callback) {
....
.success(){
callback();
}
}
控制器代码更改为
.controller('ChartController', ['$scope', '$http', 'chartService',
function($scope, $http, chartService) {
// On load
chartService.updateChartData(function(){
$scope.loading =true;
});
}]);