我在代码中的浏览器控制台中收到此错误的经过时间计算器:
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.
}
});
请帮助,我也让小提琴看看代码
答案 0 :(得分:1)
看起来我找到了这个问题。我假设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>
<强> ADDED 强>
也不确定您是否真的需要此手表功能。请记住,在您的情况下,手表在整个阵列上工作而不是内部元素。您可以提取此值scope.$eval(attrs.myCurrentTime)
。