我想显示小时、分钟和秒(实时),我在 Controller 中使用 $interval
编写了函数,但 $scope
没有更新我的 View 。
这是我的观点:
<div ng-controller="clockCtrl">
{{hour}}:{{min}}:{{sec}}
</div>
这是我的 Controller :
angular.module('myApp').controller('clockCtrl',function($scope,$interval){
$interval(callAtInterval, 1000);
});
function callAtInterval(){
console.log("this text is getting printed after each second");
var today = new Date();
h=today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
$scope.hour=h;
$scope.min=m;
$scope.sec=s;
}
函数正在被调用,但 View 没有更新。
最佳答案
您的 callAtInterval
函数是在 Controller 外部声明的,因此它无权访问 $scope
。你应该这样声明它:
angular.module('myApp').controller('clockCtrl',function($scope,$interval){
function callAtInterval(){
console.log("this text is getting printed after each second");
var today = new Date();
h=today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
$scope.hour=h;
$scope.minutes=m;
$scope.sec=s;
}
$interval(callAtInterval, 1000);
});
关于javascript - AngularJs Controller 中的实时时钟功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36866161/