Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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