[英]angular $scope variable updated but not displayed
In the below controller $scope.timer is incremented every second but in the view {{timer}}
does not reflect it's content. 在下面的控制器中,$ scope.timer每秒钟增加一次,但在视图
{{timer}}
中不反映其内容。
myapp.controller('TimeCtrl', ['$scope', function($scope){
$scope.timer = 0;
setInterval(function(){
$scope.timer = $scope.timer + 1;
console.log($scope.timer);
},1000);
}]);
I'can solve it adding $scope.$apply();
我可以添加
$scope.$apply();
来解决它 after the timer is updated why is that ? 计时器更新后为什么? Why is timer not updated ?
为什么计时器不更新?
Fiddle here : http://jsfiddle.net/wvxgzx76/1/ 在这里提琴: http : //jsfiddle.net/wvxgzx76/1/
Because setInterval
is outside the $digest
cycle - use Angulars $interval
directive instead: 因为
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);
}]);
just wrap your code into scope apply: 只需将您的代码包装到适用范围内即可:
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);
}]);
or use $interval instead of setInterval (i would prefer this): 或使用$ 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);
}]);
http://jsfiddle.net/wvxgzx76/3/ http://jsfiddle.net/wvxgzx76/3/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.