Angular $ apply不会更新视图

时间:2016-07-31 10:08:56

标签: javascript angularjs web

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

提交按钮:

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

在我的控制器中:

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

然而,它不起作用。 我尝试了不同的方法,比如$ watch service,但我得到了相同的结果。

<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>

控制器

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);
  };
}]);

付款 - 我的数组操作服务。

表格

<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>

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

1 个答案:

答案 0 :(得分:3)

$scope.$apply$scope.$digest更适合与第三方库或测试合作。在您的情况下,Angular非常了解您的更改。问题是,在提交新项目后,应再次查询驻留在服务中的payments数组(除非您直接引用该数组,否则不应进行查询)。

像这样:

查看

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

<强>控制器

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