light9
7/3/2013 - 5:54 PM

Toggle an AngularJS $watch expression. The default $watch can only be toggled once.

Toggle an AngularJS $watch expression. The default $watch can only be toggled once.

var testWatcher = toggleWatch("watchTest", function(value) {
  $log.info("Got " + value);
});

testWatcher(); // Enables
testWatcher(); // Disables
testWatcher(); // Enables again
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);
    }
  };
};