Skip to content

Instantly share code, notes, and snippets.

@deltreey
Forked from mariussoutier/togglewatch.js
Created January 26, 2016 23:05
Show Gist options
  • Select an option

  • Save deltreey/930890db340675366ce4 to your computer and use it in GitHub Desktop.

Select an option

Save deltreey/930890db340675366ce4 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