I have a watch on a data object:
$scope.$watch('data', function(after, before) {
$scope.saveData();
}, true);
I also have a modal that pops up to edit some of the data object's properties above. However, if I edit any properties through this modal, but decide to 'cancel', it still saves the edited property.
Is there a way to disable that watch when the modal pops up?
When you invoke the $watch() method, to create a binding, Angular JS returns a "de-registration" function. This function can then be used to unbind your $watch() listener - all you have to do is invoke this returned function and your $watch() listener will be removed. Save this answer.
What is the angular JS watch function? The angular JS $watch function is used to watch the scope object. The $watch keep an eye on the variable and as the value of the variable changes the angular JS $what runs a function. This function takes two arguments one is the new value and another parameter is the old value.
$watch() is used to watch changes, for example in some input fields. This function always returns old value and new value. $watchCollection() is used when trying to push something to a collection, or when removing some elements from it. This function returns previous collection and new collection.
$watch returns a function. if you call it you remove your watcher
angular docs, scroll down to $watch and take a 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 could pass the deregistration function to the modal controller. modified example from the 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 am not aware of a simple method (function call or similar) to re-enable the watcher. you will have to set it again.
modalInstance.result.then(function (data) {
$scope.data = data;
}, function () {
// callback for cancel, here you could re-apply the watcher
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With