【发布时间】:2015-07-11 23:27:56
【问题描述】:
我正在使用 Ionic 创建一个混合应用程序,它将加载一些存储在设备上的 JSON 文件。由于相同的数据将在几种不同的状态下使用,我认为存储对 JSON 请求的响应并重用它是有意义的,而不是一遍又一遍地重新读取 JSON 文件。
This question seems to address that scenario,但我似乎无法让它工作。虽然模板在我使用更简单的 $http.get().success() 请求时有效,但自从我开始尝试使用此服务以来,它从未填充过。
app.factory('localJsonService', function($http, $q) {
var localJsonService = {};
localJsonService.returnLegislators = function() {
if (this.legislators) {
return $q.when(this.legislators);
}
return $http.get('/data/legislators.json').then(function(response) {
this.legislators = response.data;
return this.legislators;
});
}
return localJsonService;
});
//old malfunctioning controller
app.controller('profileController', function($scope, $stateParams, localJsonService) {
$scope.legislators = localJsonService.returnLegislators();
$scope.legislator = $scope.legislators[$stateParams.seq_no-1];
console.log($scope.legislator); //displays undefined
});
//EDIT: newer, working controller (but still loads JSON file on each new state)
app.controller('profileController2', function($scope, $stateParams, localJsonService) {
localJsonService.getLegislators().then(function(legislators){
$scope.legislator = legislators[$stateParams.seq_no-1];
});
});
这只是对我缺少的服务的简单更改吗?还是我完全以错误的方式解决这个问题?我正在运行 AngularJS v1.3.13,但我不反对其他版本,如果这有帮助的话。
感谢您能给我的任何帮助。
【问题讨论】:
标签: angularjs ionic-framework angular-promise