gpt4 book ai didi

javascript - setTimeout 中的 Angular 变量不刷新?

转载 作者:行者123 更新时间:2023-12-03 16:51:26 24 4
gpt4 key购买 nike

我有一些问题。为什么h1值在功能改变后不刷新?应该进行刷新,因为据我所知 Angular,它总是在变量更改时刷新,或者我走错了路?

angular.module('ionicApp', ['ionic'])
.controller('MainCtrl', function($scope) {
$scope.CurrentCount = 0;
$scope.CallCounter = function(){
setTimeout(function(){
console.log($scope.CurrentCount)
if($scope.CurrentCount != 9){
$scope.CurrentCount = $scope.CurrentCount+1;
$scope.CallCounter();
}},1000);
}
});
body {
cursor: url('http://ionicframework.com/img/finger.png'), auto;
}

.container h1{
text-align:center;
color:green;
}
<html ng-app="ionicApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>Count Down</title>
<link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">
<script src="//code.ionicframework.com/nightly/js/ionic.bundle.js"></script>
</head>
<body ng-controller= "MainCtrl">
<div class="container">
<div class="spacer"></div>
<h1>{{CurrentCount}}</h1>
<div class="button button-positive" ng-click="CallCounter()">CountDown</div>
</div>

</body>
</html>

最佳答案

你应该使用 $timeout而不是 setTimeout , 因为 setTimeout没有关于 Angular 范围的信息。所以应该是

angular.module('ionicApp', ['ionic'])
.controller('MainCtrl', function ($scope, $timeout) {
$scope.CurrentCount = 0;
$scope.CallCounter = function () {
$timeout(function () {
console.log($scope.CurrentCount)
if ($scope.CurrentCount != 9) {
$scope.CurrentCount = $scope.CurrentCount + 1;
$scope.CallCounter();
}
}, 1000);
}
});

关于javascript - setTimeout 中的 Angular 变量不刷新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30434537/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com