我有一些问题。为什么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>
答案 0 :(得分:3)
setTimeout
中的更新发生在角度知识之外,因此视图未更新。在$timeout
内进行。
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);
}
});
答案 1 :(得分:3)
您应该使用$timeout
而不是setTimeout
,因为setTimeout
没有关于角度范围的信息。所以它应该是
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);
}
});
答案 2 :(得分:1)
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);
}
});
&#13;
body {
cursor: url('http://ionicframework.com/img/finger.png'), auto;
}
.container h1{
text-align:center;
color:green;
}
&#13;
<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>
&#13;