AngularJS ng-init 不工作
AngularJS ng-init does not work
当我在加载页面后立即转到 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>
$http
调用异步工作,当你调用它时,它不会在下一行执行时给你响应。要关注 ajax 你应该通过 $http
方法使用 promise
return。
为了实现同样的目标,您需要 return 服务 get
方法中的承诺对象($http
方法执行 return 的承诺对象,这有助于您通过在其 .then
函数中执行您的代码。
服务
this.get = function(){
return $http.get("harjoitus22/backend.php").then(function(res){
list = res.data;
});
};
控制器
dataservice.get().then(function(){
$scope.list = dataservice.give();
});
当我在加载页面后立即转到 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>
$http
调用异步工作,当你调用它时,它不会在下一行执行时给你响应。要关注 ajax 你应该通过 $http
方法使用 promise
return。
为了实现同样的目标,您需要 return 服务 get
方法中的承诺对象($http
方法执行 return 的承诺对象,这有助于您通过在其 .then
函数中执行您的代码。
服务
this.get = function(){
return $http.get("harjoitus22/backend.php").then(function(res){
list = res.data;
});
};
控制器
dataservice.get().then(function(){
$scope.list = dataservice.give();
});