html,这是我的代码,以下是详细信息。我的目的是使用angularJS实现倒计时功能。
var app = angular.module('myCountDown', []);
app.controller("Countdown",function($scope){
$scope.start = function(){
var temp = $scope.inputValue;
setInterval(function(){
if(temp<1){
return ;
}
temp -= 1;
$scope.count = temp;
console.log($scope.count);
},1000);
}
})
&#13;
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body ng-app="myCountDown">
<div ng-controller="Countdown">
<input type="text" ng-model="inputValue">
<button ng-click="start()">开始</button>
<input type="text" ng-model="count">
</div>
<script src="angular.min.js"></script>
<script src="app.js"></script>
</body>
</html>
&#13;
我已在控制台中打印结果,但网页中没有输出。
谢谢你!答案 0 :(得分:2)
使用$ scope。$ apply()查看更改或使用 $interval
,建议使用 setTimeout
。< / p>
<强>样本强>
var app = angular.module('myCountDown', []);
app.controller("Countdown", function($scope, $interval) {
$scope.start = function() {
var temp = $scope.inputValue;
$interval(function() {
if (temp < 1) {
return;
}
temp -= 1;
$scope.count = temp;
console.log($scope.count);
}, 1000);
}
})
<!doctype html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body ng-app="myCountDown">
<div ng-controller="Countdown">
<h1> {{count}}</h1>
<input type="text" ng-model="inputValue">
<button ng-click="start()">开始</button>
{{count}}
<input type="text" ng-model="count">
</div>
</body>
</html>
答案 1 :(得分:1)
setInterval
将耗尽角度范围。你可以使用$interval
。
还记得在创建新的interval
之前清除之前的var app = angular.module('myCountDown', []);
app.controller("Countdown", function($scope, $interval) {
$scope.start = function() {
var temp = $scope.inputValue;
if ($scope.sampleInterval) {
$interval.cancel($scope.sampleInterval);
}
$scope.sampleInterval = $interval(function() {
if (temp < 1) {
return;
}
temp -= 1;
$scope.count = temp;
console.log($scope.count);
}, 1000);
}
})
。
参考下面的例子。
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myCountDown" ng-app="myCountDown">
<div ng-controller="Countdown">
<input type="text" ng-model="inputValue">
<button ng-click="start()">开始</button>
<input type="text" ng-model="count">
</div>
<script src="angular.min.js"></script>
<script src="app.js"></script>
</div>
{{1}}
答案 2 :(得分:0)
我知道如何解决这个问题。 我们可以修改js文件。
var app = angular.module('myCountDown', []);
app.controller("Countdown",function($scope){
$scope.start = function(){
var temp = $scope.inputValue;
setInterval(function(){
if(temp<1){
return ;
}
temp -= 1;
$scope.count = temp;
$scope.$apply();
console.log($scope.count);
},1000);
}
})
&#13;