当我在加载页面后马上去list.html时,它不会给我显示列表。我需要先去form.html,然后再回到list.html,然后它给我列表。当我在控制器中有$http函数时,它按照我的要求工作,但是现在它们在服务中,它们不再像以前那样工作了。
app.js
app.service("dataservice", function($http){
var list = [{}];
this.get = function(){
$http.get("harjoitus22/backend.php").success(function(response){
list = response;
});
};
this.save = function(newcontact){
$http({
method: 'post',
url: 'harjoitus22/backend.php',
data: newcontact,
header: 'Access-Control-Allow-Origin: *'
}).success(function(response){
list = response;
});
};
this.give = function(){
return list;
};
});
app.controller("mainController", function($scope, $location, dataservice){
$scope.save = function(){
dataservice.save($scope.newcontact);
$scope.newcontact = {};
$location.path("/list");
$scope.list = dataservice.give();
};
$scope.get = function(){
dataservice.get();
$scope.list = dataservice.give();
};
});list.html
<tbody ng-init="get()">
<tr ng-repeat="object in list">
<td>{{object.nimi}}</td>
<td>{{object.email}}</td>
<td>{{object.ruoka}}</td>
<td>{{object.sauna}}</td>
</tr>
</tbody>发布于 2016-05-13 13:43:11
$http调用异步工作,当您调用它时,它不会在下一行执行时给出响应。为了关注ajax,您应该使用promise通过$http方法返回。
为了实现同样的目标,您需要从服务get方法中返回允诺对象($http方法确实返回承诺对象,它通过将代码放在.then函数中来帮助您执行代码)。
服务
this.get = function(){
return $http.get("harjoitus22/backend.php").then(function(res){
list = res.data;
});
};控制器
dataservice.get().then(function(){
$scope.list = dataservice.give();
});https://stackoverflow.com/questions/37211527
复制相似问题