我创建了一个带有选项卡的离子项目,这些选项卡使用services.js中的代码显示动态列表:
.factory('Interventions', function($http) {
var interventions = {};
$http({
method: 'POST',
url: 'http://172.20.1.1/list.php'
}).success(function(data, status, headers, config) {
interventions = data;
});
return {
all: function() {
return interventions;
},
get: function(iid) {
return interventions[iid];
}}
})
问题是我的应用程序在我加载页面时没有首先显示列表,但只有当我刷新它(使用doRefresh)或者当我转到其他选项卡并返回到第一个时。 有解决方案可以解决这个问题吗?
提前谢谢
我的代码i ncontroller.js:
.controller('InterventionCtrl', function($scope, $http, Interventions) {
$scope.interventions = Interventions.all();
$scope.doRefresh = function() {
$http.get('http://172.20.1.1/list.php')
.success(function(newItems) {
$scope.interventions = newItems;
})
.finally(function() {
// Stop the ion-refresher from spinning
$scope.$broadcast('scroll.refreshComplete');
});
};
})
.controller('InterventionDetailCtrl', function($scope, $stateParams, Interventions) {
$scope.intervention = Interventions.get($stateParams.iid);
});
和我的观点:
<ion-view title="Interventions">
<ion-content>
<ion-list>
<ion-item ng-repeat="intervention in interventions" type="item-text-wrap" href="#/tab/interventions/{{intervention.ID}}">
<h3>{{intervention.Nom}}</h3>
</ion-item>
</ion-list>
</ion-content>
</ion-view>
答案 0 :(得分:0)
Interventions.all()发出一个异步的http请求。调用all()时,您无法保证数据可用。 所以all()都不能返回数据。你必须传递一个类似的回调(未经测试):
var interventions = {};
var doRequest = function(callback) {
$http({
method: 'POST',
url: 'http://172.20.1.1/list.php'
}).success(function(data, status, headers, config) {
interventions = data;
callback(data);
});
})
return {
all: function(callback) {
if (interventions) {
callback(interventions)
} else {
doRequest(callback)
}
},
get: function(iid,callback) {
if (interventions) {
callback(interventions[iid])
} else {
doRequest(function(data){
callback(data[iid])
})
}
}
}
在你的控制器中:
Interventions.all(function(interventions) {
$scope.interventions = interventions;
}
Interventions.get(iid,function(intervention) {
$scope.intervention = intervention;
}
您可以在此处找到有关异步的更多信息:How do I return the response from an asynchronous call?