gpt4 book ai didi

javascript - AngularJS ng-init 不起作用

转载 作者:行者123 更新时间:2023-11-30 11:58:42 25 4
gpt4 key购买 nike

当我在加载页面后立即转到 list.html 时,它没有显示列表。我需要先转到 form.html,然后返回 list.html,然后它会给我列表。当我在 Controller 中有 $http 函数时,它按我想要的方式工作,但现在它们已投入使用,它们不再像以前那样工作了。

应用程序.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();
};
});

列表.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

为了实现同样的目的,您需要从服务 get 方法返回 promise 对象($http 方法确实返回了 promise 对象,这有助于您通过将在它的 .then 函数中。

服务

this.get = function(){
return $http.get("harjoitus22/backend.php").then(function(res){
list = res.data;
});
};

Controller

dataservice.get().then(function(){
$scope.list = dataservice.give();
});

关于javascript - AngularJS ng-init 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37211527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com