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', ...)