作用域是't更新$apply使用

scope isn't updating on $apply use

本文关键字:更新 apply 使用 作用域      更新时间:2023-09-26

我有一段$scope文本,应该动态更新。

<span ng-bind="user.balance"></span>

按下按钮后,会收到新的余额值,并应在此处显示。

$http.post('/transaction/send', transaction).success(function(sender) {
          console.log("http response");
          $scope.user = sender;
          console.log($scope.user.balance);
          $timeout(function() {$scope.$apply(); console.log("apply used");}, 1000);
        });

在控制台日志中,任何内容都会被正确地接收和显示,但它仍然不会更新视图中的范围。我做错了什么?我正在使用$timeout来消除"$digest已经在使用"

您应该使用angular.extend(dst, src),而不是将新对象分配给$scope.user变量。通过这样做,您将把新属性合并到旧对象中;这将使您的绑定继续工作。最后,你应该有这样的东西:

$http.post('/transaction/send', transaction).success(function(sender) {
      console.log("http response");
      angular.extend($scope.user, sender);
      console.log($scope.user.balance);
});

请注意,这只是一个浅合并,对于深合并,你应该看看这个讨论或这个讨论。