AngularJS视图未更新模型更改

shu*_*111 72 javascript angularjs

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

HTML

<div ng-app="test">  
        <p ng-controller="TestCtrl">  
            {{testValue}}  
        </p>  
    </div>
Run Code Online (Sandbox Code Playgroud)

JS

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

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

        setInterval(function() {
            console.log($scope.testValue++);
        }, 500);
    });
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/N2G7z/

有任何想法吗?

Bor*_*nov 117

正如上面提到的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);
});
Run Code Online (Sandbox Code Playgroud)

  • 迭戈·维埃拉的回答更好。经验法则是:只要有可能,就使用 Angular 的提供者/服务,他们自己进行应用。 (2认同)

Die*_*ira 36

只需使用$ 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);
});
Run Code Online (Sandbox Code Playgroud)


Dav*_*yon 28

setTimout在角度之外执行.您需要使用$timeout服务才能工作:

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

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

        $timeout(function() {
            console.log($scope.testValue++);
        }, 500);
    });
Run Code Online (Sandbox Code Playgroud)

原因是角度的双向绑定使用脏检查. 这是一篇关于角度脏检查的好文章. $scope.$apply()开始一个$digest周期.这将适用于绑定. 为您$timeout处理$apply,因此它是使用超时时使用的推荐服务.

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


小智 8

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

$ rootScope:inprog Action已在进行中

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