很难理解 $watch。我将它与计时器一起使用来增加一个值 - 如果用户想继续,则尝试在五秒钟后提示用户。如果他们选择“取消”,则计时器停止计数。
小提琴在这里:http: //jsfiddle.net/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();
}
}
}
checkTime 函数在页面加载时触发一次,我希望它会触发每个增量,因为 $scope.counter 变量每秒都在变化。