最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论