admin管理员组文章数量:1415139
Having a hard time understanding $watch. I'm using it with a timer to increment a value - attempting to prompt a user after five seconds if they'd like to continue. If they select 'Cancel', then the timer stops counting.
Fiddle is here: /
// Increment with $timeout
$scope.counter = 0;
$scope.onTimeout = function () {
$scope.counter++;
mytimeout = $timeout($scope.onTimeout, 1000);
};
var mytimeout = $timeout($scope.onTimeout, 1000);
// Watch
$scope.$watch($scope.counter, checkTime);
function checkTime() {
console.log($scope.counter);
if ($scope.counter === 5) {
var check = confirm('Do you want to continue?');
if (check === false) {
$scope.stop();
}
}
}
The checkTime function fires once on page load, I was hoping it would fire every increment as the $scope.counter variable is changing every second.
Having a hard time understanding $watch. I'm using it with a timer to increment a value - attempting to prompt a user after five seconds if they'd like to continue. If they select 'Cancel', then the timer stops counting.
Fiddle is here: http://jsfiddle/nicktest222/VuuEK/4/
// Increment with $timeout
$scope.counter = 0;
$scope.onTimeout = function () {
$scope.counter++;
mytimeout = $timeout($scope.onTimeout, 1000);
};
var mytimeout = $timeout($scope.onTimeout, 1000);
// Watch
$scope.$watch($scope.counter, checkTime);
function checkTime() {
console.log($scope.counter);
if ($scope.counter === 5) {
var check = confirm('Do you want to continue?');
if (check === false) {
$scope.stop();
}
}
}
The checkTime function fires once on page load, I was hoping it would fire every increment as the $scope.counter variable is changing every second.
Share Improve this question asked Oct 10, 2013 at 22:47 NickNick 5926 gold badges12 silver badges21 bronze badges2 Answers
Reset to default 5$watch
takes an angular expression, this is what you want:
$scope.$watch('counter', checkTime);
To expand on Jason's answer, you can have a $watch
on any variable of any scope since the parameter is just a string, so inside your controller, you can have a watch on $rootScope
as well!
$scope.$watch('counter', ...)
$rootScope.$watch('rootCounter', ...)
本文标签: javascriptAngularJSwatch and timeoutStack Overflow
版权声明:本文标题:javascript - AngularJS - $watch and $timeout - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745228033a2648699.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论