Disable and enable watches in AngularJS

I have a clock on a data object:

$scope.$watch('data', function(after, before) { $scope.saveData(); }, true); 

I also have a modal that appears to edit some of the properties of the data object above. However, if I edit any properties using this modal, but deciding to "cancel", it saves the saved property.

Is there a way to disable this clock when modal pop-ups?

+6
source share
1 answer

$ watch returns a function. if you call it, you remove your observer

angular docs , scroll down to $ watch and look at the return value

 var myWatcher = $scope.$watch('data', function(after, before) { $scope.saveData(); }, true); myWatcher(); // removes your watcher 

EDIT : with angular -ui-bootstrap you can pass the deregistration function to the modal controller. modified example from docs :

  var modalInstance = $modal.open({ templateUrl: 'myModalContent.html', controller: ModalInstanceCtrl, size: size, resolve: { items: function () { return { data: data myWatcher: myWatcher // you can call items.myWatcher() in your modal controller }; } } }); 

but I don’t know a simple method (function call or similar) to re-enable the observer. You will have to install it again.

  modalInstance.result.then(function (data) { $scope.data = data; }, function () { // callback for cancel, here you could re-apply the watcher }); 
+4
source

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


All Articles