我在运行时间计算器的代码中的浏览器控制台中收到此错误:
Uncaught Error: [$rootScope:infdig]
我从应用程序启动的当前时间计算耗时。
这是我的 html:
<div ng-app="time">
<div ng-controller="Ctrl2">
Elapsed time: <span my-current-time="[date,format]"></span>
</div>
</div>
这是 JavaScript 代码:
function Ctrl2($scope) {
$scope.date = new Date();
$scope.format = 'M/d/yy h:mm:ss a';
}
angular.module('time', [])
// Register the 'myCurrentTime' directive factory method.
// We inject $timeout and dateFilter service since the factory method is DI.
.directive('myCurrentTime', function($timeout, dateFilter) {
// return the directive link function. (compile function not needed)
return function(scope, element, attrs) {
var format, // date format
timeoutId; // timeoutId, so that we can cancel the time updates
var since;
// used to update the UI
function updateTime() {
element.text(dateFilter(since, format));
element.text( (((new Date()).getTime() - since.getTime())/(1000*60)%60) + " minutes, since " + dateFilter(since, format));
}
// watch the expression, and update the UI on change.
//scope.$watch(attrs.myCurrentTime, function(value) {
// format = value;
// updateTime();
//});
scope.$watch(attrs.myCurrentTime, function(value) {
since = value[0];
format = value[1];
updateTime();
});
// schedule update in one second
function updateLater() {
// save the timeoutId for canceling
timeoutId = $timeout(function() {
updateTime(); // update DOM
updateLater(); // schedule another update
}, 1000);
}
// listen on DOM destroy (removal) event, and cancel the next UI update
// to prevent updating time ofter the DOM element was removed.
element.bind('$destroy', function() {
$timeout.cancel(timeoutId);
});
updateLater(); // kick off the UI update process.
}
});
请帮忙,我也做了 fiddle 看看代码
最佳答案
看来我已经找到了问题所在。我假设 angular 在每次评估时都会创建新数组,因此它总是会触发观察者
function Ctrl2($scope) {
$scope.date = new Date();
$scope.format = 'M/d/yy h:mm:ss a';
$scope.options = [$scope.date, $scope.format]; //<--line added
}
<div ng-app="time">
<div ng-controller="Ctrl2">
Elapsed time: <span my-current-time="options"></span> //<-- binding change.
</div>
</div>
已添加
也不确定您是否真的需要此 watch 功能。请记住, watch 在您的情况下适用于整个阵列而不是内部元素。您可以提取值 scope.$eval(attrs.myCurrentTime)
.
关于javascript - Uncaught Error : [$rootScope:infdig] when implementing an elapsed time calculator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25103966/