【发布时间】:2017-07-19 13:54:10
【问题描述】:
我有一个计时器,我正在编写它作为我在 AngularJS 中的第一个应用程序。我一直在尝试自学角度,但我相信我的模型设置方式可能存在根本性的脱节。虽然我可以通过我的 console.log 打印输出在 Web 控制台中看到更新的值,但 html 端的计时器似乎没有更新。
var myApp = angular.module('countdownTimer', []);
myApp.service('timerService',['$http','$timeout', function($http, $timeout){
var time = 180;
var self = this;
this.getPrettyTime = function(){
var minutes = time/60;
var seconds = time - minutes * 60;
if (seconds < 10){
myDateObject.date = minutes + ":0" + seconds;
}
else{
myDateObject.date = minutes + ":" + seconds;
}
return myDateObject;
}
var myDateObject = {
date: null
}
var onTimeout = function() {
time = time - 1;
if (time > 0){
console.log(time);
mytimeout = $timeout(onTimeout, 1000);
}
else{
time = 180;
mytimeout = $timeout(onTimeout, 1000);
}
}
this.start = function() {
$timeout(onTimeout, 1000);
}
}]);
myApp.controller('CounterController', ['$timeout','$scope', 'timerService', function($timeout, $scope, timerService){
/**$scope.counter = 180;
**/
//var date = new Date(null);
//date.setSeconds(timerService.getTime());
$scope.myDateObject = timerService.getPrettyTime();
$scope.start = function(){
timerService.start();
}
$scope.stop = function(){
$timeout.cancel(mytimeout);
}
}]);
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Example </title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
<script src="app2.js"></script>
</head>
<body data-ng-app="countdownTimer">
<div data-ng-controller="CounterController">
{{myDateObject.date}}
<button data-ng-click="stop()">Stop</button>
<button data-ng-click="start()">Start</button>
</div>
</body>
</html>
正如您在上面的示例中看到的,网页上的计时器没有更新。我的逻辑是否存在脱节(我是 Angular 新手,所以我很想知道我哪里出错了)还是我完全误解了 Angular 功能?
谢谢
【问题讨论】:
-
从您的代码中我可以看出,
myDateObject没有任何更新,您需要一个可以更新此值的代码,但您的逻辑设计看起来不太可能这样做 -
同意@codtex。我花了很多时间试图让它围绕您现有的代码工作,但它似乎不太可行。考虑重构一下,以便
myDateObject可以根据服务更改在控制器中更新。
标签: javascript html angularjs controller dynamic-programming