在下面的 Controller 中 $scope.timer 每秒递增,但在 View 中 {{timer}}
不反射(reflect)其内容。
myapp.controller('TimeCtrl', ['$scope', function($scope){
$scope.timer = 0;
setInterval(function(){
$scope.timer = $scope.timer + 1;
console.log($scope.timer);
},1000);
}]);
我可以在计时器更新后添加 $scope.$apply();
来解决这个问题,为什么呢?为什么计时器没有更新?
最佳答案
因为 setInterval
位于 $digest
循环之外 - 请改用 Angulars $interval
指令:
myapp.controller('TimeCtrl', ['$scope', '$interval', function($scope, $interval){
$scope.timer = 0;
$interval(function(){
$scope.timer = $scope.timer + 1;
console.log($scope.timer);
},1000);
}]);
关于javascript - Angular $scope 变量已更新但未显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26658120/