我正在使用AngularJS驱动的页面,我需要在只读输入文本字段中显示一个运行时钟(与data-ng-model绑定的双向).为了模拟正在运行的时钟,我使用带有setTimeout的
JavaScript调度程序每隔1000毫秒调用一个函数,这会更新$scope’d属性值,而该值依次绑定到该输入文本字段.不知何故,输入字段中的值没有得到更新.所以我放了一个< pre />使用jQuery选择器标记并更新其内容.这工作正常,所以我需要帮助获取输入文本字段值也每秒更新.
我为这个例子设置了一个jsFiddle.
HTML如下:
<body data-ng-app="formApp"> <div data-ng-controller="FormCtrl"> Current Date and Time <input type="text" data-ng-model="formData.currentDateTime" readonly="readonly" size="60" /> </div> <pre id="currentDateTime" style="font-size:1.5em;"> </pre> </body>
AngularJS app模块和控制器声明如下:
(function() { var formApp = angular.module("formApp",[]); formApp.controller("FormCtrl",function ($scope) { $scope.formData = {}; $scope.formData.currentDateTime = new Date().toString(); (function updateCDT() { $scope.formData.currentDateTime = new Date().toString(); document.getElementById("currentDateTime").innerHTML = $scope.formData.currentDateTime; setTimeout(updateCDT,1000); })(); }); })();
解决方法@H_301_14@
你需要使用$scope.$apply()或angulars $timeout来反映更改,因为setTimeout超出了angularjs的范围
使用$scope.$apply()
将$scope.$apply()应用于setTimeout(function(){},1000)的匿名函数中,然后调用实际函数,如下所示
(function updateCDT() {
$scope.formData.currentDateTime = new Date().toString();
document.getElementById("currentDateTime").innerHTML
= $scope.formData.currentDateTime;
setTimeout(function(){
$scope.$apply();
updateCDT()
},1000);
fiddle for $scope.$apply()
使用$timeout(别忘了把它注入控制器)
(function updateCDT() {
$scope.formData.currentDateTime = new Date().toString();
document.getElementById("currentDateTime").innerHTML
= $scope.formData.currentDateTime;
$timeout(updateCDT,1000);
})();
fiddle为$timeout
使用$scope.$apply()
将$scope.$apply()应用于setTimeout(function(){},1000)的匿名函数中,然后调用实际函数,如下所示
(function updateCDT() { $scope.formData.currentDateTime = new Date().toString(); document.getElementById("currentDateTime").innerHTML = $scope.formData.currentDateTime; setTimeout(function(){ $scope.$apply(); updateCDT() },1000);
fiddle for $scope.$apply()
使用$timeout(别忘了把它注入控制器)
(function updateCDT() { $scope.formData.currentDateTime = new Date().toString(); document.getElementById("currentDateTime").innerHTML = $scope.formData.currentDateTime; $timeout(updateCDT,1000); })();
fiddle为$timeout