javascript 范围变量以角度更新,但更改未反映给用户

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26866394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:37:14  来源:igfitidea点击:

scope variable updated in angular but change is not reflected to user

javascriptangularjsscope

提问by Coop

I have some angular variables set like so:

我有一些像这样设置的角度变量:

$scope.pane = [];
$scope.pane.count = 0;
$scope.pane.max = 5;

Then I display the variables in the HTML like this:

然后我在 HTML 中显示变量,如下所示:

{{pane.count}}

This works fine and displays 0as expected.

这工作正常并按0预期显示。

Now if I update the variable at any point, the update does happen (I can see using console.log) but the printed version in the HTML does not update.

现在,如果我在任何时候更新变量,更新就会发生(我可以使用 console.log 看到),但 HTML 中的打印版本不会更新。

E.g.

例如

setTimeout(function(){
  $scope.pane.count = 1;
},1000);

I am using Angular v1.3. What am I doing wrong?

我正在使用 Angular v1.3。我究竟做错了什么?

回答by halilb

In order to let angular know about changes, you have to use angular wrapperfor timeout.

为了让 angular 了解更改,您必须使用 angular包装器进行超时。

Try this:

试试这个:

$timeout(function() {
  $scope.pane.count = 1;
}, 1000);

Generally, when you have a structure outside angular world(such as jQuery plugin) that changes values, you have to call $scope.$apply() to let angular know about them.

一般来说,当你有一个 angular 世界之外的结构(比如 jQuery 插件)改变值时,你必须调用 $scope.$apply() 来让 angular 知道它们。

$scope.$apply();

回答by sylwester

setTimeout is outside angularjs scope so you need to use $scope.$apply or $timout please see sample demo below

setTimeout 超出 angularjs 范围,因此您需要使用 $scope.$apply 或 $timout 请参阅下面的示例演示

var app = angular.module('app', []);

app.controller('homeCtrl', function($scope, $timeout) {

  $scope.pane = [];
  $scope.pane.count = 0;
  $scope.pane.count2 = 0;
  $scope.pane.max = 5;

  setTimeout(function() {
    $scope.$apply(function() {
      $scope.pane.count = 1;
    })

  }, 1000);

  $timeout(function() {
    $scope.pane.count2 = 5;
  }, 2000);


});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


<div ng-app="app">
  <div ng-controller="homeCtrl">
<h3>setTimeout</h3>
    Count 1: {{pane.count}}<br/>
    <h3>$timeout</h3>
    Count 2: {{pane.count2}}
  </div>
</div>