Skip to content

Instantly share code, notes, and snippets.

@mariussoutier
Last active August 13, 2018 23:55
Show Gist options
  • Save mariussoutier/5921001 to your computer and use it in GitHub Desktop.
Save mariussoutier/5921001 to your computer and use it in GitHub Desktop.
Toggle an AngularJS $watch expression. The default $watch can only be toggled once.
var toggleWatch = function(watchExpr, fn) {
var watchFn;
return function() {
if (watchFn) {
watchFn();
watchFn = undefined;
console.log("Disabled " + watchExpr);
} else {
watchFn = $scope.$watch(watchExpr, fn);
console.log("Enabled " + watchExpr);
}
};
};
var testWatcher = toggleWatch("watchTest", function(value) {
$log.info("Got " + value);
});
testWatcher(); // Enables
testWatcher(); // Disables
testWatcher(); // Enables again
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment