Pausing $ watch in AngularJS

See this jsfiddle ; I have two sets of input fields with scope variables attached via an ng model.

Think of this system as a Google-style search, with a single search box and advanced search.

  • When one search input is updated (in the example, a ), there is a function for updating the corresponding “advanced” inputs. I implemented this in $scope.$watch('a', ... ) .

  • When the "advanced" search input changes, it is also necessary to update one input (implemented in $scope.$watch('b', ... ) .

Of course, these two generate a feedback loop - a updates b , and then vice versa, ad infinitum is not good! I would like the command “pause another observer” to be issued at the beginning of each of the above hours, then (after updating another variable) to issue the “restart observer” command to prevent this.

Is there any way to do this?

+4
source share
1 answer

I put together a simple example.

 <body ng-app="app" ng-controller="myTestCntrl"> <input type="button" ng-click="increaseCounter()" value="Click me" /> clicked: {{counter}z} times<br/> <input type="button" ng-click="pauseWatcher()" value="{{watcherBtnText}}" /> watched: {{internalCounter}} times<br/> <strong>Number of $$watchers in $scope:</strong> {{$$watchers.length}} <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script> <script type="text/javascript"> angular.module('app', []) .controller('myTestCntrl', function myTestCntrl($scope) { $scope.counter = 0; $scope.pauseWatching = false; $scope.watcherBtnText = 'Pause'; $scope.internalCounter = -1; $scope.increaseCounter = function() { $scope.counter++; }; var listenerFn = function() { if ($scope.pauseWatching) { namedWatcher(); } else { $scope.internalCounter++; }; } var namedWatcher = $scope.$watch('counter', listenerFn); $scope.pauseWatcher = function() { if ($scope.pauseWatching) { $scope.watcherBtnText = 'Pause'; $scope.pauseWatching = false; $scope.internalCounter--; namedWatcher = $scope.$watch('counter', listenerFn); } else { $scope.watcherBtnText = 'Continue'; $scope.pauseWatching = true; namedWatcher(); }; } }); </script> </body> 

demo on jsfiddle: http://jsfiddle.net/BuriB/63sND/

+1
source

Source: https://habr.com/ru/post/1481214/


All Articles