gpt4 book ai didi

javascript - Angular 在 POST 后重新加载另一个 Controller

转载 作者:可可西里 更新时间:2023-11-01 13:48:32 26 4
gpt4 key购买 nike

正如我在标题中提到的,我只是想在 POST 到我的代码后重新加载(不刷新页面)另一个具有更新数据的 Controller 。

将数据保存到数据库没有问题。

脚本

var app = angular.module('userBase', []);
app.controller('listUsers', function($scope,$http) {
$http.get("req.php")
.then(function (response) {
$scope.userloop = response.data.reqresponse;
});

});

app.controller('addUsers', function($scope,$http) {

$scope.buttonFire = function() {
$http.post("add.php",{'name': $scope.name, 'email': $scope.email})
.success(function(data, status, headers, config){

});
}

});

查看

<div ng-controller="listUsers">
<ul ng-repeat="x in userloop">
<li>{{ x.Name }} - {{ x.Email }} </li>
</ul>
</div>

<div ng-controller="addUsers">
<p>Name: <input type="text" ng-model="name"></p>
<p>Email: <input type="text" ng-model="email"></p>
<span ng-bind="name"></span> and <span ng-bind="email"></span><br/>
<button ng-click="buttonFire()">Send or Save</button>
</div>

最佳答案

您可以借助事件基础设施解决您的问题:

app.controller('listUsers', function($scope,$http) {
$scope.on('newuser', function(event, data){
load(true);

//or you can do this: (without row above, i.e. without performing
//request to the server)
//$scope.$apply(function(){
// $scope.userloop.push(data);
//});
});

var load = function(isEvent){
$http.get("req.php")
.then(function (response) {
$scope.userloop = response.data.reqresponse;
if(isEvent)
$scope.$digest();
});
};
load();
});

app.controller('addUsers', function($scope,$http) {

$scope.buttonFire = function() {
var newuser = {'name': $scope.name, 'email': $scope.email};
$http.post("add.php", newuser)
.success(function(data, status, headers, config){
$scope.$parent.$broadcast('newuser', newuser);
});
}

});

关于javascript - Angular 在 POST 后重新加载另一个 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38389233/

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