AngularJS视图不会在模型更改时更新

AngularJS view not updating on model change

本文关键字:更新 模型 视图 AngularJS      更新时间:2023-09-26

我试图弄清楚 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/

有什么想法吗?

正如上面提到的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);
});

只需使用$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);
});
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 脏检查的好文章。 $scope.$apply()拉开了$digest周期的序幕。 这将应用绑定。 $timeout为您处理$apply,因此建议在使用超时时使用该服务。

本质上,绑定发生在$digest周期中(如果值不同(。

不要使用 $scope.$apply() angular 已经使用它,它可能会导致此错误

$rootScope:正在进行的行动

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