gpt4 book ai didi

javascript - Angular 循环没有更新

转载 作者:行者123 更新时间:2023-11-28 23:57:52 37 4
gpt4 key购买 nike

刚开始使用 angular。我成功地使用 php 从数据库中保存和检索数据。我还可以在列表项中循环数据,但是当我添加新用户时,列表不会更新,只有当我刷新浏览器时,它才会显示新添加的用户

这是我的html代码:

<div>
<ul ng-init="get_user()">
<li ng-repeat="user in userInfo ">{{user.user_name}}<a href="" ng-click="prod_delete(product.id)"> --> Delete</a></li>
</ul>
</div>

这是我的 app.js 代码:

var app = angular.module('AddUser', ['ui.bootstrap']);

app.controller('AppCtrl', function($scope, $http){
$scope.userInfo = [];

/** function to add details for a user in mysql referecing php **/
$scope.save_user = function() {

$http.post('db.php?action=add_user',
{
'user_name' : $scope.user_name,
'user_email' : $scope.user_email
}
)

.success(function (data, status, headers, config) {
$scope.userInfo.push(data);
console.log("The user has been added successfully to the DB");
console.log(data);
})

.error(function(data, status, headers, config) {
console.log("Failed to add the user to DB");
});
}

/** function to get info of user added in mysql referencing php **/
$scope.get_user = function() {
$http.get('db.php?action=get_user').success(function(data)
{
$scope.userInfo = data;
console.log("You were succesfull in show user info");
//console.log(data);
})
}

});

最佳答案

当您进行后调用时,它通过服务器方法将数据保存到数据库,但在后调用成功时,您将该数据推送到 userInfo 对象中,这在技术上听起来是错误的。

我希望您在 post 调用成功后使用 $scope.get_user() 创建一个 ajax 以从数据库中获取新数据。

代码

$scope.save_user = function() {
$http.post('db.php?action=add_user', {
'user_name' : $scope.user_name,
'user_email' : $scope.user_email
}).success(function (data, status, headers, config) {
//$scope.userInfo.push(data); //remove this line
$scope.get_user(); //this will fetch latest record from DB
console.log("The user has been added successfully to the DB");
console.log(data);
}).error(function(data, status, headers, config) {
console.log("Failed to add the user to DB");
});
}

关于javascript - Angular 循环没有更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31033371/

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