2016-03-03 76 views
2

如何重置$timeout,並禁用$watch()

回答

2

雙方的關鍵是分配的結果是:

var myTimer = $timeout(function() { /* ... */ }, 5000); 
$timeout.cancel(yourTimer); 

您可以通過註銷函數返回清除$watch()該函數爲一個變量。

清理超時,只是「.cancel()」是:

var customTimeout = $timeout(function() { 
// arbitrary code 
}, 55); 
$timeout.cancel(customTimeout); 

這同樣適用於「$間隔()」。

要禁用手錶,只需調用它即可。

var deregisterWatchFn = $rootScope.$watch(‘someGloballyAvailableProperty’, function (newVal) { 
if (newVal) { 
// we invoke that deregistration function, to disable the watch 
deregisterWatchFn(); 
... 
} 
}); 
+0

我明白了,謝謝。 – JackinC

+0

答案的來源可能是 - https://www.codementor.io/angularjs/tutorial/angularjs-interview-questions-sample-answers –

0

您可以通過使用$timeout.cancel清除$timeout像這樣:

var dereg = $scope.$watch(function() { /* ... */ }); 
dereg(); // watcher is now gone 
0

你已經得到了大部分答案,但另一點可能是有用的,你應該經常清理在相關範圍內被破壞的手錶,所以下面的模式是非常有用的:

$scope.$on('$destroy', $scope.$watch(function() { /* ... */ }); 

這將確保$watch總是在銷燬範圍時自動取消。

當然,如果你想手動銷燬手錶,你也必須保存結果,以便你可以調用它,但是這種模式可以讓你在大多數情況下避免這種情況。