Sha*_*lor 1 javascript model-view-controller controller setinterval angularjs
我正在尝试根据控制器中的Javascript Date对象在视图中显示当前时间.我的控制器看起来像这样:
myApp.controller('DateCtrl', function($scope) {
var date = new Date();
$scope.minutes = date.getMinutes();
$scope.hours = date.getHours();
$scope.seconds = date.getSeconds();
var updateTime = function() {
var date2 = new Date();
$scope.minutes = date2.getMinutes();
$scope.hours = date2.getHours();
$scope.seconds = date2.getSeconds();
}
$scope.clickUpdate = function() {
setInterval(updateTime, 1000);
}
});
Run Code Online (Sandbox Code Playgroud)
在我看来,我只是:
<div ng-controller="DateCtrl">
<div>This is the hour: {{ hours }}</div>
<div>This is the minute: {{ minutes }}</div>
<div>This is the second: {{ seconds }}</div>
<button ng-click="clickUpdate()">Click Update Here!</button>
</div>
Run Code Online (Sandbox Code Playgroud)
由于某种原因,该setInterval()方法只能工作一次,我无法让它updateTime()每隔1秒保持运行一样.我提出了一个简单的console.log()陈述,并且每1秒运行一次......所以我很困惑.
我也检查了$scope.watch(),$scope.digest()但我不太确定如何使用/如果我应该在这种情况下使用它们.
编辑:进一步检查,看起来好像setInterval工作正常,updateTime()每1秒调用一次,但范围内的值在每次调用后都没有反映在我的视图中.
这是因为您正在从角度世界(setInterval)之外更改范围.你必须$apply改变:
var updateTime = function() {
$scope.$apply(function(){
var date2 = new Date();
$scope.minutes = date2.getMinutes();
$scope.hours = date2.getHours();
$scope.seconds = date2.getSeconds();
});
}
Run Code Online (Sandbox Code Playgroud)
或使用角度感知功能,如$timeout.检查此问题中的 @asgoth答案以创建角度感知 setInterval()功能.
| 归档时间: |
|
| 查看次数: |
5839 次 |
| 最近记录: |