Register and unregister angular js watch

In my application, I want to check a checkbox for users to toggle whether the application periodically requests new data in the background. I have set the clock to poll the data. And I know that if I assign a variable to this clock on creation, I can call that variable and the clock is disabled / unregistered. My problem is when users click on the text box, I want the clock to come to life. I haven't found a better way to do this. Here is my example fiddle that illustrates the problem somewhat. I think if I could get it to work there I might be able to tweak it. The part that doesn't work is the part where the watch should go back online:

 if ($scope.counter === 15) {
        $scope.$watch('counter', theWatchFunction);
        $scope.test = "back on";
    }

      

+3


source to share


2 answers


You cannot simply deregister the observer and wait for it to re-register again. When you start myWatch()

, everything inside theWatchFunction

will never start again. You can register a new observer, but not inside theWatchFunction

.



You can, for example, re-register the observer counter

in the observer time

: http://jsfiddle.net/bmleite/Lw3Lp/

+4


source


You were close, the reason your jsfiddle is not working is because on counter 7 you are canceling the clock. Since your code for turning on the clock was included in the WatchFunction, it never gets called because the clock is turned off, so the function is no longer executed.

I put a check on the counter to go back to the clock in your timeout function and it seems to work correctly.



    $timeout(function () {
        $scope.time = new Date();
        $scope.counter++;
        if ($scope.counter === 15) {
           myWatch = $scope.$watch('counter', theWatchFunction);
        }
    }, 1000);

      

I have forked the fiddle demonstrating a working version that should help you. Hope it helps!

0


source







All Articles