如何更新列表的ng-repeat视图?

时间:2014-05-20 20:37:38

标签: javascript angularjs angularjs-ng-repeat

This simple fiddle使用ng-repeat显示列表。但是如果我从DOM外部更改列表(在这种情况下,使用计时器),列表视图不会更新。

我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:2)

因为您从Angular外部调用setTimeout(fn),所以摘要周期不知道变量已更新。

尝试使用Angular的$timeout服务,以便在运行该函数时,Angular将知道应用摘要周期。

Updated example

编辑:使用$scope.$apply()的示例,以防$timeout不是正在使用的内容。

来自评论:“是的,您可以if(!$scope.$$phase) $scope.$apply()运行。如果您只是消化本地范围,还有$scope.$digestJSFiddle

控制器内的代码示例:

$scope.lines = lines;
setTimeout(function() {
    lines.push({text: 'new text'});
    console.log('Line added: ' + lines.length);
    if ( !$scope.$$phase ) $scope.$apply();
}, 1000);