在下面的控制器中,$ scope.timer每秒递增一次,但在视图{{timer}}
中没有反映它的内容。
myapp.controller('TimeCtrl', ['$scope', function($scope){
$scope.timer = 0;
setInterval(function(){
$scope.timer = $scope.timer + 1;
console.log($scope.timer);
},1000);
}]);
我可以解决它在更新计时器后添加$scope.$apply();
的原因是什么?为什么计时器没有更新?
答案 0 :(得分:1)
因为setInterval
超出$digest
周期 - 请改用Angularjs $interval
指令:
myapp.controller('TimeCtrl', ['$scope', '$interval', function($scope, $interval){
$scope.timer = 0;
$interval(function(){
$scope.timer = $scope.timer + 1;
console.log($scope.timer);
},1000);
}]);
答案 1 :(得分:1)
将代码包装到范围适用:
var myapp = angular.module('myapp', []);
myapp.controller('TimeCtrl', ['$scope', function($scope){
$scope.timer = 0;
setInterval(function(){
$scope.$apply(function () {
$scope.timer = $scope.timer + 1;
console.log($scope.timer);
});
},1000);
}]);
或使用$ interval而不是setInterval(我更喜欢这个):
var myapp = angular.module('myapp', []);
myapp.controller('TimeCtrl', ['$scope', '$interval', function($scope,$interval){
$scope.timer = 0;
$interval(function(){
$scope.timer = $scope.timer + 1;
console.log($scope.timer);
},1000);
}]);