简体   繁体   English

范围不会在$ apply use上更新

[英]scope isn't updating on $apply use

I have a piece of $scope text that should update dynamically. 我有一个$ scope文本,应该动态更新。

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

after pushing a button, new value of balance is received and should be displayed here. 按下按钮后,将收到新的余额值,应在此处显示。

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

In console log anything is received and displayed properly, but it still doesn't update scope in the view. 在控制台日志中,任何内容均已接收并正确显示,但仍不会更新视图中的作用域。 What am I doing wrong? 我究竟做错了什么? I'm using $timeout to get rid of "$digest is already in use" 我正在使用$ timeout摆脱“ $ digest已经在使用中”

You should use angular.extend(dst, src) instead of assigning a new object to your $scope.user variable. 您应该使用angular.extend(dst, src)而不是将新对象分配给$scope.user变量。 By doing so, you will be merging the new properties into your older object; 这样,您将把新属性合并到您的旧对象中。 this will keep your binding working. 这将使您的绑定工作正常。 In the end, you should have something like this: 最后,您应该具有以下内容:

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

Mind you, this only does a shallow merge, for a deep merge, you should look at this discussion or this one . 请注意,这仅是一个浅层合并,对于深层合并,您应该查看此讨论 讨论

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM