【问题标题】:AngularJS view not updating on model changeAngularJS视图不更新模型更改
【发布时间】:2013-12-02 22:03:21
【问题描述】:

我正在尝试弄清楚 Angular 是如何工作的,但在模型更改时无法更新我的视图..

HTML

<div ng-app="test">  
        <p ng-controller="TestCtrl">  
            {{testValue}}  
        </p>  
    </div>

JS

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

    app.controller('TestCtrl', function ($scope) {
       $scope.testValue = 0;

        setInterval(function() {
            console.log($scope.testValue++);
        }, 500);
    });

http://jsfiddle.net/N2G7z/

有什么想法吗?

【问题讨论】:

  • 除了下面的答案,如果你仍然想使用 settimeout 你必须使用 scope.$apply()
  • $scope.$apply() 是我需要的。我正在处理的项目中的模型在用户交互后更新。我实际上并没有使用超时或间隔,但很高兴知道将来如何将它们与角度一起使用。感谢您的回答!
  • 这是一篇有趣的文章,您将在其中了解有关 $digest 循环的更多信息sitepoint.com/understanding-angulars-apply-digest

标签: javascript angularjs


【解决方案1】:

正如上面提到的 Ajay beniwal,你需要使用 Apply 来开始消化。

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

app.controller('TestCtrl', function ($scope) {
   $scope.testValue = 0;

    setInterval(function() {
        console.log($scope.testValue++);
        $scope.$apply() 
    }, 500);
});

【讨论】:

  • 迭戈维埃拉的回答更好。经验法则是:尽可能使用 Angular 的提供者/服务,他们自己来申请。
  • 在我写那条评论的时候,没有任何 $intervals 它只是对 setInterval 的包装。它的外观也不那么保存:阅读更多:docs.angularjs.org/api/ng/service/$interval
  • 这是一个hack,angular有自己的计时器,应该使用$interval来更新观察者
  • 太棒了!非常感谢!
  • 非常感谢!!!
【解决方案2】:

只需使用$interval

这是您修改的代码。 http://plnkr.co/edit/m7psQ5rwx4w1yAwAFdyr?p=preview

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

app.controller('TestCtrl', function ($scope, $interval) {
   $scope.testValue = 0;

    $interval(function() {
        $scope.testValue++;
    }, 500);
});

【讨论】:

    【解决方案3】:

    setTimout 在 Angular 之外执行。您需要使用$timeout 服务才能使其工作:

    var app = angular.module('test', []);
    
        app.controller('TestCtrl', function ($scope, $timeout) {
           $scope.testValue = 0;
    
            $timeout(function() {
                console.log($scope.testValue++);
            }, 500);
        });
    

    原因是 Angular 中的双向绑定使用脏检查。 This is a good article 了解 Angular 的脏检查。 $scope.$apply() 启动 $digest 循环。这将应用绑定。 $timeout 为您处理 $apply,因此建议在使用超时时使用它。

    本质上,绑定发生在$digest 循环期间(如果看到的值不同)。

    【讨论】:

      【解决方案4】:

      不要使用$scope.$apply() angular 已经使用了它会导致这个错误

      $rootScope:inprog 操作已在进行中

      如果使用两次,请使用$timeout或间隔

      【讨论】:

        猜你喜欢
        • 2014-02-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多