gpt4 book ai didi

javascript - Angular $apply 不更新 View

转载 作者:行者123 更新时间:2023-11-29 19:11:15 24 4
gpt4 key购买 nike

我有一个表单,当我提交它时,它会将一些对象推送到我的数组中。在该表格下方,我有一个表格显示该数组中的所有项目。我希望我的表格在推送新项目时自动更新(无需刷新页面)。

提交按钮:

<button type="submit" class="btn btn-default" ng-click="updateTable()">Pay</button>

在我的 Controller 中:

  $scope.updateTable = function() {
setTimeout(function () {
$scope.$apply();
$scope.$digest();
}, 0);
};

但是,它不起作用。我尝试了不同的方法,例如 $watch 服务,但我得到了相同的结果。

表格

<div class="row paytable">
<div class="col-xs-10 col-xs-offset-1">
{{payments.length}}
<table class="table table-hover ">
<tr>
<td>Id</td>
<td>Amount</td>
<td>Cause</td>
</tr>
<tr ng-repeat="item in payments">
<td>{{item.id}}</td>
<td>{{item.amount}}</td>
<td>{{item.cause}}</td>
</tr>
</table>
</div>
</div>

Controller

app.controller('mainController', [ 'user', '$rootScope', '$scope', 'payment', '$timeout', function(user, $rootScope, $scope, payment, $timeout) {

user.getUsers();
user.newUser();
$rootScope.currentUser = user.currentUser();

$scope.payments = payment.getPayments();
$scope.newPayment = payment.newPayment;

$scope.updateTable = function() {
setTimeout(function () {
console.log('apply ------------');
$scope.$apply();
$scope.$digest();
}, 0);

};

$scope.showPayMessage = function() {
console.log('im here');
$scope.showSM = true;
$timeout(function() {
$scope.showSM = false;
}, 2000);
};
}]);

payment - 我的数组操作服务。

表单

<div class="newpay row" >
<div class=" col-xs-10 col-xs-offset-1">
<h1>Hello, {{currentUser.name}}</h1>
<h4 ng-show="showSM" class="bg-success">Payment confirmed</h4>
<form name="inputform" ng-submit="newPayment(amount, cause); showPayMessage();">
<div class="form-group">
<label for="exampleInputEmail1">Amount</label>
<input type="number" name="amount" ng-model="amount" class="form-control" id="exampleInputEmail1" placeholder="Amount" required>

</div>
<div class="form-group">
<label for="exampleInputPassword1">Cause</label>
<input type="text" name="cause" ng-model="cause" class="form-control" id="exampleInputPassword1" placeholder="Cause" required>

</div>

<button type="submit" class="btn btn-default" ng-click="updateTable()">Pay</button>
</form>
</div>
</div>
payments: {{payments.length}}
<payments-table payments="payments"></payments-table>

为了显示该表,我创建了指令。

最佳答案

$scope.$apply$scope.$digest 更适合使用 3rd 方库或测试。在您的情况下,Angular 很清楚您的更改。问题是,驻留在服务中的 payments 数组应该在提交新项目后再次查询(除非您直接引用该数组,否则不应进行任何查询)。

像这样:

查看

<form name="inputform" ng-submit="onSubmit()">

Controller

$scope.onSubmit = function() {
newPayment($scope.newItemAmount, $scope.newItemCause); // Assuming they are properties in the controller
showPayMessage();
$scope.payments = payment.getPayments(); // getting the updated array
}

关于javascript - Angular $apply 不更新 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38682885/

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