javascript - AngularJS - $watch and $timeout - Stack Overflow

Having a hard time understanding $watch. I'm using it with a timer to increment a value - attempti

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 badges
Add a ment  | 

2 Answers 2

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745228033a4617553.html

相关推荐

  • javascript - AngularJS - $watch and $timeout - Stack Overflow

    Having a hard time understanding $watch. I'm using it with a timer to increment a value - attempti

    4小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信